C 5ms solution, time O(n), constant space


  • 0
    P
    int maxProfit(int prices[], int n){
        if ((!n)||(n==1)) return 0;
        int profit=INT_MIN;
        int minp=prices[0];
        for (int i=1; i<n; ++i)
        {
            if (prices[i]-minp>profit)
                profit=prices[i]-minp;
            if (prices[i]<minp)
                minp=prices[i];
        }
        if (profit<=0)
            return 0;
        return profit;
    }

Log in to reply
 

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