Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kanrourou/abf2bf2f7719a7ff8e54e4dcc930b4bc to your computer and use it in GitHub Desktop.

Select an option

Save kanrourou/abf2bf2f7719a7ff8e54e4dcc930b4bc to your computer and use it in GitHub Desktop.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len < 2)return 0;
vector<int> dp(2, 0);
dp[1] = max(0, prices[1] - prices[0]);
int maxDiff = dp[0] - prices[2], e = 0;
for(int i = 2; i < len; ++i, e ^= 1)
{
maxDiff = max(maxDiff, dp[e] - prices[i]);
int localMax = max(maxDiff + prices[i], max(prices[i] - prices[0], prices[i] - prices[1]));
dp[e] = max(dp[e ^ 1], localMax);
}
return dp[e ^ 1];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment