C++ DP 6ms


  • 1
    T
    int maxProfit(vector<int>& prices) {
            int n = prices.size();
            if (n==0) return 0;
            int* DP = new int[n]; //the maximum profit at position i
            DP[0] = 0; 
            int smax = DP[0];
            int hold = prices[0];
            for (int i=1; i < n; i++){
                if (prices[i]>hold) DP[i] = prices[i]-prices[i-1] + DP[i-1]; 
                else {
                DP[i] = 0;
                hold = prices[i];
                }
                smax = max(smax, DP[i]);
            }
            return smax;
        }
    

Log in to reply
 

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