10 lines concise solution in O(n) time and O(1) space


  • 2
    L
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int profit = 0, highest_price = 0;
            for (int i = prices.size() - 1; i >= 0; --i) {
                highest_price = max(highest_price, prices[i]);
                profit = max(profit, highest_price - prices[i]);
            }
            return profit;
        }
    };

Log in to reply
 

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