您的位置:首页 > 其它

LeetCode题解:123. Best Time to Buy and Sell Stock III

2017-12-10 15:38 465 查看
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).
原题地址

上一篇文章写了交易一次能获得的最大利润。该题目要求买卖两次得到最大利润。按照上篇文章的思路,可以同样衍生出两种思路;

思路1:

本题是交易两次,可以分成两个一次交易的问题来解,如果我告诉你,第一次的交易是在哪一天结束的。那么这个问题就变成了两个一次交易的问题。可以用上一篇文章的思路1来解;可以枚举所有第一次交易完成的天数的可能。

当枚举到第k天的时候,会重复计算k-1天时候的数据。用数组来存储之前计算过的状态。第一次交易的计算从前向后计算,第二次交易的计算从后向前计算,因为这样才能利用之前计算的状态。

计算第一次交易时,minPrice存储当前最低的价格,firstTran[i]记录到第i天的时候,能获得的最大利润。

minPrice = min{minPrice,prices[i-1]}

firstTran[i] = max{firstTran[i-1],prices[i-1]-minPrice}

计算第二次交易时,maxPrice存储当前的最高价格,secondTran[i] 记录第i天到最后一天,能获得的最大利润。

maxPrice = max{maxPrice,prices[i+1]}

secondTran[i] = max{secondTran[i+1],maxPrice-prices[i-1]}

最后枚举所有第一次交易完成的可能,求最大值。

class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int[] firstTran = new int[prices.length + 2];
int[] secondTran = new int[prices.length + 2];
int minPrice = Integer.MAX_VALUE;
for (int i = 1; i <= prices.length; i++) {
minPrice = Integer.min(minPrice, prices[i - 1]);
firstTran[i] = Integer.max(firstTran[i - 1], prices[i - 1] - minPrice);
}
int maxPrice = Integer.MIN_VALUE;
for (int i = prices.length; i >= 1; i--) {
maxPrice = Integer.max(maxPrice, prices[i - 1]);
secondTran[i] = Integer.max(secondTran[i + 1], maxPrice - prices[i - 1]);
}
int maxAns = 0;
for (int i = 1; i <= prices.length; i++) {
maxAns = Integer.max(maxAns, firstTran[i] + secondTran[i]);
}
return maxAns;
}
}

思路2:

按照上一篇博客中的写到,无非就是通过第一次的卖控制第一次的最大值,第二次的卖
b1ba
控制整体的最大值。

public class Solution {  

    public int maxProfit(int[] prices) {  

        int buy = Integer.MIN_VALUE, sell = 0;  

        for (int price : prices) {  

            buy = Integer.max(buy, -price);  

            sell = Integer.max(sell, buy + price);  

        }  

        return sell;  

    }  



后面再加两行,返回最后的sell即可。

class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE, sell1 = 0, sell2 = 0;
for (int price : prices) {
buy1 = Integer.max(buy1, -price);
sell1 = Integer.max(sell1, buy1 + price);
buy2 = Integer.max(buy2, sell1 - price);
sell2 = Integer.max(sell2, buy2 + price);
}
return sell2;
}
}后面的这种思路更加通用一些,推荐后面的这种做法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: