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,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
相关文章推荐
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- 【LeetCode从零单刷】Best Time to Buy and Sell Stock I, II, With Cooldown
- 【LEETCODE】309-Best Time to Buy and Sell Stock with Cooldown
- LeetCode 309 Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown LeetCode
- [leetcode 309]Best Time to Buy and Sell Stock with Cooldown--买卖股票with冷却期(DP法)
- leetcode - Best Time to Buy and Sell Stock with Cooldown
- LeetCode-Best Time to Buy and Sell Stock with Cooldown
- leetcode -- Best Time to Buy and Sell Stock with Cooldown -- 不理解
- leetcode_309 Best Time to Buy and Sell Stock with Cooldown
- LeetCode Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- LeetCode -- Best Time to Buy and Sell Stock with Cooldown
- [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期
- leetcode Best Time to Buy and Sell Stock with Cooldown
- [leetcode] Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- leetcode——309——Best Time to Buy and Sell Stock with Cooldown
- LeetCode Best Time to Buy and Sell Stock with Cooldown