Simple C++ solution with backward traversing.


  • 0
    S
    class Solution {
    public:
        struct transaction{
            int buy;
            int sell;
        };
        int maxProfit(vector<int>& prices) {
            if (prices == NULL || prices.size() < 2) return 0;
            int max_profit = 0;
            int max_sell = 0;
            for(auto it = prices.rbegin(); it != prices.rend() - 1; ++it){
                max_sell = max(max_sell, *it);
                max_profit = max(max_profit, max_sell - *(it + 1));
            }
            return max_profit;
        }
    };
    

Log in to reply
 

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