动态规划
dp[i][0] 表示当天什么都不操作
dp[i][1] 表示当天买进
dp[i][2] 表示当天卖出
状态转移就好写出了
class Solution {
public:
long long int dp[10005][3];
int maxProfit(vector<int>& prices) {
if (prices.size() == 0)
return 0;
dp[0][0] = 0;
dp[0][1] = 0 - prices[0];
dp[0][2] = INT32_MIN;
for (int i = 1; i < prices.size(); i++)
{
dp[i][0] = INT32_MIN;
dp[i][1] = INT32_MIN;
dp[i][2] = INT32_MIN;
for (int j = 0; j < i; j++)
{
if (dp[j][1] != INT32_MIN)
{
dp[i][2] = max(dp[i][2], dp[j][1] + prices[i]);
}
}
dp[i][0] = max(dp[i - 1][0], dp[i - 1][2]);
dp[i][1] = dp[i - 1][0] - prices[i];
}
return max(dp[prices.size()-1][0], max(dp[prices.size()-1][1], dp[prices.size()-1][2]));
}
long long int max(long long int a, long long int b)
{
return a > b ? a : b;
}
};