Problem Description
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
Some Details
- 标准的简单DP题目
Solution
DP没怎么切,这题虽然难度不高但是既然切到了就赶快写了,毕竟作业难以完成= =。
买入,卖出,冷却,三状态,ok
f[i][0] 第i天手上没货的最优获利
f[i][1] 第i天手上有货的最优获利
f[i][2] 第i天进入冷却的最优获利
转移方程:
f[i][0]=max(f[i-1][0],f[i-1][2])
//前一天就没货或者前一天冷却
f[i][1]=max(f[i-1][0]-price[i],f[i-1][1])
//前一天就有货或者今天买入
f[i][2]=f[i-1][1]+price[i];
//前一天有货今天卖了
结束思密达。
Code
class Solution {
public:
int maxProfit(vector<int>& prices) {
int f[10100][4],siz=prices.size();
if (siz==0) return 0;
f[0][0]=0;
f[0][1]=prices[0]*-1;
f[0][2]=0;
for (int i=1;i<siz;i++)
{
f[i][0]=max(f[i-1][0],f[i-1][2]);
f[i][1]=max(f[i-1][0]-prices[i],f[i-1][1]);
f[i][2]=f[i-1][1]+prices[i];
}
int ans=f[siz-1][0];
ans=max(ans,f[siz-1][1]);
ans=max(ans,f[siz-1][2]);
return ans;
}
};