123. Best Time to Buy and Sell Stock III

15 篇文章 0 订阅
3 篇文章 0 订阅

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:
现在让我们来看看Best Time to Buy and Sell Stock这个系列的第三道题。题目中说最多可以买卖两次。所以,解决方法是进行两次DP,两次以当前的第i天为分界线。第一次是从前往后遍历,如果在第i天之前发生了一次交易,那么最大profit就通过跟121. Best Time to Buy and Sell Stock一样的方法,用minPricevector<int>maxProfit1来分别保存截至目前的最低价格,和截止每一天的最高收益这个数组。第二次是从后往前遍历,假设在第i天以后发生了一次交易,那么我们用maxPrice来保存今天的价格和过去的最高价格之间更高的那一个,然后用maxProfit2来保存maxPrice - prices[i]和当前maxProfit2中更大的那一个。同时在第二次遍历的时候鼠标求对每一个imaxProfit1 + maxProfit2中的最大值,就是最后需要的结果了。

代码如下:
class Solution {
public:
int maxProfit(vector& prices) {
if(prices.empty()) return 0;

vector<int> maxProfit1(prices.size(), 0);
int minPrice = INT_MAX;
int maxPrice = INT_MIN;
int maxProfit2 = 0;
int res = 0;

for(int i = 0; i < prices.size(); ++i){
    minPrice = min(minPrice, prices[i]);
    maxProfit1[i] = max(maxProfit1[i - 1], prices[i] - minPrice);
}

for(int i = prices.size() - 1; i >= 0; --i){
    maxPrice = max(maxPrice, prices[i]);
    maxProfit2 = max(maxPrice - prices[i], maxProfit2);
    res = max(res, maxProfit1[i] + maxProfit2);
}
return res;
}

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值