您的位置:首页 > 其它

Leetcode Best Time to Buy and Sell Stock with Cooldown

2017-03-02 11:30 369 查看
题意:给出每个时刻股票的价格,每天只能买入或卖出,买入或卖出后第二天不能交易。

思路:DP,dp[i][j] 表示在第i天买入,第j天卖出的最大利润,转态方程为:dp[i][j] = max(dp[i][j - 1],  max(dp[i - 2][k])。

class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> dp(prices.size(), 0);
int max_pro = 0;
vector<int> dp_pre(prices.size(), 0);

for(int i = 0; i < prices.size(); ++ i) {
for(int j = i; j < prices.size(); j ++) {
int temp_max = 0;
if(i - 2 >= 0) temp_max = dp_pre[i - 2];

if(prices[j] - prices[i] > 0) dp[j] = prices[j] - prices[i] + temp_max;
else dp[j] = temp_max;
if(j - 1 > 0) dp[j] = max(dp[j], dp[j - 1]);
max_pro = max(max_pro, dp[j]);
dp_pre[j] = max(dp_pre[j], dp[j]);
//printf("%d ", dp[i][j]);
}
//cout << endl;
}

return max_pro;
}

};1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp