Easy solution in C, O(n) time complexity and O(1) space complexity


  • 8
    C
    int maxProfit(int price[], int n)
    {
        int ret = 0, past = 0;
        for(int i = 1; i < n; i++)
        {
    	    ret += price[i] - price[i-1];
    	    if(ret < 0) ret = 0;
    	    if(ret > past) past = ret;
        }
        return past;
    }

Log in to reply
 

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