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).
思路:因为要交易两笔,所以可以定位下标i,在i左边为第一笔交易的最大值p1[i],i右边为第二笔交易的最大值p2[i],因此可以把题目转换为求p1[i]和p2[i]的和的最大值。
分三步走,第一步:求p1[i]从左往右算
第二步:求p2[i]从右往左算
第三步:变量i,求p1[i] +p2[i]的最大值
class Solution {
public:
int maxProfit(vector<int> &prices) {
int ans = 0,len = prices.size();
if(len == 0) return 0;
int p1[len],p2[len];
memset(p1,0,sizeof(int)*len);
memset(p2,0,sizeof(int)*len);
int min = prices[0];
for(int i = 1;i < len;i ++){
p1[i] = prices[i] - min > p1[i - 1] ? prices[i] - min : p1[i - 1];
min = prices[i] < min ? prices[i] : min;
}
int max = prices[len - 1];
for(int i = len - 2;i >= 0;i --){
p2[i] = max - prices[i] > p2[i + 1] ? max - prices[i] : p2[i + 1];
max = prices[i] > max ? prices[i] : max;
}
ans = p1[0] + p2[0];
for(int i = 1;i < len;i ++)
ans = ans > p1[i] + p2[i] ? ans : p1[i] + p2[i];
return ans;
}
};
本文介绍了一种算法,用于计算给定股票价格数组中通过最多两次买卖交易获得的最大利润。该算法分为三个步骤:首先计算左侧最大利润数组,其次计算右侧最大利润数组,最后通过遍历寻找两者组合的最大值。
679

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



