Best Time to Buy and Sell Stocks III
1 2 3 4 5 6 7 8 9 10 11 12
| int Solution::maxProfit(const vector<int> &A) { if(A.size() < 2) return 0; vector<long long> dp(A.size() + 2, INT_MIN), dpp(A.size() + 2,INT_MIN); long long ma = A.back(), res = 0; for(int i = A.size() - 2; i >= 0; i--) { dp[i] = max(dp[i+1], ma - A[i]); dpp[i] = max(dpp[i + 1], dp[i+2] + A[i + 1]); ma = max(ma,1ll*A[i]); res = max(res, dpp[i] - A[i]); } return max(res,dp[0]); }
|