***Leetcode 188. Best Time to Buy and Sell Stock IV | dp
2018-02-28 20:54
399 查看
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
请教了一个ACM金的好基友... dp还是一直太弱
思路:
dp[i][j][0]表示前i天,进行j次买和j次卖,也就是进行了完整的j次交易
dp[i][j][1]表示前i天,进行j次买和j-i次卖
那么
dp[i][j][1] = max( dp[i-1][j][1], dp[i-1][j-1][0] - prices[i] ),j>=1 && j <= k
dp[i][j][0] = max( dp[i-1][j][0], dp[i-1][j][1] + prices[i] ), j>=1 && j <= k
实际i这一个维度存储上是不必要的
简化的方程:
dp[j][1] = max( dp[j-1][0] - prices[i] ), j>=1 && j <= k
dp[j][0] = max( dp[j][1] + prices[i] ), j>=1 && j <= k
请教了一个ACM金的好基友... dp还是一直太弱
思路:
dp[i][j][0]表示前i天,进行j次买和j次卖,也就是进行了完整的j次交易
dp[i][j][1]表示前i天,进行j次买和j-i次卖
那么
dp[i][j][1] = max( dp[i-1][j][1], dp[i-1][j-1][0] - prices[i] ),j>=1 && j <= k
dp[i][j][0] = max( dp[i-1][j][0], dp[i-1][j][1] + prices[i] ), j>=1 && j <= k
实际i这一个维度存储上是不必要的
简化的方程:
dp[j][1] = max( dp[j-1][0] - prices[i] ), j>=1 && j <= k
dp[j][0] = max( dp[j][1] + prices[i] ), j>=1 && j <= k
const int SZ = 1e6 + 5; int dp[SZ][2]; // 1: buy 0:sell class Solution { public: int maxProfit(int k, vector<int>& prices) { int ans = 0; if (k >= prices.size()/2) { for (int i = 1; i < prices.size(); i++) { if (prices[i] > prices[i-1]) { ans += prices[i] - prices[i-1]; } } return ans; } for (int i = 0; i <= k; i++ ) { dp[i][1] = INT_MIN; dp[i][0] = 0; } for (int i = 0; i < prices.size(); i++) { for (int j = 1; j <= k; j++) { int tmp = dp[j][1]; dp[j][1] = max(dp[j][1], dp[j-1][0] - prices[i]); dp[j][0] = max(dp[j][0], tmp + prices[i]); } } return dp[k][0]; } };
相关文章推荐
- 【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法(C++)
- leetcode 188. Best Time to Buy and Sell Stock IV 最大子段和
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- [Leetcode] Best Time to Buy and Sell Stock I,II,III,IV
- [leetcode][DP] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock IV
- LeetCode--Best Time to Buy and Sell Stock IV(DP + 滚动数组)
- leetcode_188 Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock I II III IV 股票买卖
- [LeetCode][Java] Best Time to Buy and Sell Stock IV
- LeetCode——Best Time to Buy and Sell Stock IV
- LeetCode188:Best Time to Buy and Sell Stock IV
- Leetcode Best Time to Buy and Sell Stock IV(最大子段和)
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- LeetCode OJ Best Time to Buy and Sell Stock I II III IV
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode - Best Time to Buy and Sell Stock I && II && III && IV
- leetcode解题报告:188 Best Time to Buy and Sell Stock IV
- LeetCode Best Time to Buy and Sell Stock III && Best Time to Buy and Sell Stock IV
- LeetCode: Best Time to Buy and Sell Stock IV