(LeetCode 309)最佳买卖股票时机含冷冻期 [dp + 逆向思维]
2019-01-18 01:30
375 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/STILLxjy/article/details/86533479
309. 最佳买卖股票时机含冷冻期
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
分析:
卖出的后一天为冷冻期,表明在买入的前一天一定不能卖出。
dp[i] = max(dp[i-1], dp[j-2] + prices[i] - prices[j]) 其中prices[i] > prices[j]
AC代码:
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n == 0 || n == 1) return 0; int dp[n+2]; int ans = 0; memset(dp,0,sizeof(dp)); for(int i=1;i<n;i++) { dp[i] = dp[i-1]; for(int j=i-1;j>=0;j--) { if(prices[i] > prices[j]) { if(j-2 < 0) { dp[i] = max(dp[i], prices[i] - prices[j]); } else { dp[i] = max(dp[i], prices[i]-prices[j]+dp[j-2]); } } } ans = max(ans,dp[i]); } return ans; } };
相关文章推荐
- LeetCode 123. 买卖股票的最佳时机 III
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- leetcode-买卖股票的最佳时机 II
- Leetcode121: 买卖股票的最佳时机
- leetcode122. 买卖股票的最佳时机 II
- LeetCode:买卖股票的最佳时机 II
- leetcode-买卖股票的最佳时机(动态规划)
- Leetcode122:买卖股票的最佳时机 II
- [Leetcode]123.买卖股票的最佳时机3
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- Leetcode 121. 买卖股票的最佳时机
- [Leetcode]2018.3.22买卖股票的最佳时机 II
- LeetCode - 122. 买卖股票的最佳时机 II
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- Leetcode 买卖股票的最佳时机 II
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- LeetCode 122. 买卖股票的最佳时机 II
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机