Quite easy, share my C code with explanation


  • 10
    Y

    ###1. Calculate prices[i+1]-prices[i]

    ###2. Turn the array prices[] = [1,2,4,2,5,7,2,4,9,0] into
    difference[] = [+1,+2,-2,+3,+2,-5,+2,+5,-9]

    ###3. Then add all positive numbers sum = 1+2+3+2+2+5 = 15 in difference
    ###4. Return 15

    The code is a simplified and optimized version.

    #Code:

    int maxProfit(int prices[], int n){
        int profit = 0;
        for(int i=0;i<n-1;i++){
            int temp = prices[i+1]-prices[i];
            if(temp>0)
                profit += temp;
        }
        return profit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.