C++: buy at low and sell at high


  • 0
    T
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if(prices.size() == 0)
                return 0;
            int low = prices[0]; // buy at low and sell at high
            int n = prices.size();
            int profit = 0;
            int i;
            for(i=0; i<n; i++)
            {
                if(prices[i] < low)
                    low = prices[i];
                if(prices[i] - low > profit)
                    profit = prices[i] - low;
            }
            return profit;
        }
    };

Log in to reply
 

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