C++: buy at low (lower) and sell at high (higher)


  • 0
    T
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if(n==0)
                return 0;
            int value = 0;
            int profit = 0;
            int low = prices[0];
            
            int i;
            for(i=0; i<n; i++)
            {
                if(prices[i] < low)
                    low = prices[i];
                else if(prices[i] > low)
                {
                    if(profit < prices[i] - low)
                        profit = prices[i] - low;
                    if(i+1<n && prices[i+1] < prices[i])
                    {
                        value = value + profit;
                        profit = 0;
                        low = prices[i+1];
                    }
                }
            }
            value = value + profit;
            return value;
        }
    };

Log in to reply
 

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