您的位置:首页 > 其它

LeetCode:买卖股票的最佳时机 IV

2019-04-09 16:33 148 查看

题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/description/

买卖股票的最佳时机 III题解         https://blog.csdn.net/smile__dream/article/details/81700476
有两个参考:https://www.geek-share.com/detail/2710946775.html

https://blog.csdn.net/Bendaai/article/details/81144338

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

输入: [2,4,1], k = 2
输出: 2
解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例 2:

输入: [3,2,6,5,0,3], k = 2
输出: 7
解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
     随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
思路:无非四种状态 当天买入不买或者卖出不卖 ,我们得到状态转移方程 

        buy[i]=max(buy[i],sell[i-1]-prices)    //buy[i]代表第i笔买入自己还剩的钱 买入则减去当天的价格

        sell[i]=max(sell[i],buy[i]+prices[i])   //selle[i]代表第i笔卖出后自己还剩的钱 卖出即加入当天的价格
 

[code]class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
vector<int> P;
if (prices.empty() || k == 0) return 0;
int l = prices[0], r = 0, xx = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] < r) P.push_back(l), P.push_back(r), xx += r - l, l = prices[i], r = 0;
else l = min(l, prices[i]), r = max(r, prices[i]);
}
if (r) P.push_back(l), P.push_back(r), xx += r - l;
if (P.empty()) return 0;
int n = P.size(), M;
if (k >= n / 2) return xx;
vector<int> sell(k + 1, 0), buy(k + 1, -0x3f3f3f3f);//代表当天第k次sell/buy状态时,当天为止的收入
for (int day = 0; day < n; ++day) {
for (int i = k; i>0; --i)
buy[i] = max(buy[i], sell[i - 1] - P[day]), sell[i] = max(sell[i], buy[i] + P[day]);
}
return sell[k];
}
};

 

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