My 12ms concise c++ DP solution -- 10 lines


  • 0
    D
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            // f[i] = max(f[i-1] + prices[i] - prices[i-1], f[i-1])
            // f[0] = 0
            int maxSum = 0, sum = 0;
            for(int i = 1; i < prices.size(); i++) {
                sum += prices[i] - prices[i-1];
                maxSum = max(maxSum, sum);
                sum = max(sum, 0);
            }
            return maxSum;
        }
    };

Log in to reply
 

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