C++. linear time. constant memory. simple solution. with comments


  • 4
    A
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int min = INT_MAX, max = INT_MIN;
            int n = prices.size();
            if(n == 0)return 0;
            for(int i = 0 ; i < n; i++){
                if(prices[i] < min)
                    min = prices[i];        //update the minimum found this till point
                if(max < prices[i] - min)
                    max = prices[i]-min;    //calculate profit based on minimum found yet
            }
            return max;
        }
    };

  • 0
    S
    This post is deleted!

Log in to reply
 

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