O(n) C Solution of 4ms with O(1) space


  • 1
    R
    Here we have to find min value till ith element and profit will be the difference between ith element & min so far.
    
    int maxProfit(int* p, int pS) {
        int i, min=p[0], prof=0;
        for(i=1; i<pS; i++)
            if(p[i]>min)
                prof = prof > p[i]-min ? prof : p[i]-min;
            else
                min = p[i];
        return prof;
    }

Log in to reply
 

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