C++ Simple solution


  • 1
    # code block
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.empty()) return 0;
            int ans = 0;
            int buy = prices[0];
            for (int i = 1; i < prices.size(); ++i) {
                int profit = prices[i] - buy;
                if (profit > 0) {
                    ans = max(ans, profit);
                }
                else {
                    buy = prices[i]; 
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

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