题目链接:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
题目描述:
用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。
思路:
最多交易两次。可以以i天为分界线,一个记录以prices[i]为结尾的最大收益(即i天之前的最大收益,从前往后),一个记录以prices[i]为开头的最大收益(i天之后的最大收益,从后往前)。
preProfit[i]+postProfit[i]为总的最大收益。比较最大收益找出最大值。
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
if(len==0){
return 0;
}
int* preProfit=new int [len];
int* postProfit=new int [len];
int minPrice=prices[0];
preProfit[0]=0;
for(int i=1;i<len;i++){
minPrice=min(minPrice,prices[i]);
preProfit[i]=max(preProfit[i-1],prices[i]-minPrice);
}
int maxPrice=prices[len-1];
postProfit[len-1]=0;
for(int i=len-2;i>=0;i--){
maxPrice=max(maxPrice,prices[i]);
postProfit[i]=max(postProfit[i+1],maxPrice-prices[i]);
}
int maxRes=preProfit[0]+postProfit[0];
for(int i=1;i<len;i++){
if(maxRes<preProfit[i]+postProfit[i]){
maxRes=preProfit[i]+postProfit[i];
}
}
return maxRes;
}
};

本文介绍了一种解决LeetCode上股票买卖最佳时机III问题的方法,通过前后遍历数组记录最大收益,实现两次交易条件下的最大利润计算。
589

被折叠的 条评论
为什么被折叠?



