题目:
Say you have an array for which the i th 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天的价格。
设计一个算法来寻找最大的利润。您最多可以完成两个事务。
注意:
您可能不会同时进行多个交易(即,您必须在再次购买之前出售股票)。
思路:
1.buyFirst 记录的是第一次购买时那一天你能买到的最低价格,因为是第一次购买,所以会出现有负债的情况
2.resultFirst 代表的是你买入的那一天到现在你卖出的时候,能得到多少钱
3.buySecond 记录之前已经进行第一次买卖后,用第一次得到钱来购买股票
4.resultSecond 代表的就是两次利润最大值了
如果之前你第二次交易没有进行,那么buyFirst,buySecond 和resultFirst,resultSecond都是没有变化的。
思路大概就是这个样子,和之前 最佳时间买入卖出股票1思路差不多,只是多了1次买卖罢了。
这题也可以使用动态规划,如果有兴趣的朋友可以去看下这个博客
动态规划解决
代码:
public int maxProfit(int[] prices) {if( prices == null || prices.length <=0) {return 0;}int buyFirst = Integer.MIN_VALUE;int resultFirst = 0;int buySecond = Integer.MIN_VALUE;int resultSecond = 0;for(int i=0;i<prices.length;i++) {//第一次购买,所以应该是负债多少buyFirst = Math.max(buyFirst, -prices[i]);//第一次卖,赚的钱resultFirst = Math.max(resultFirst, buyFirst+prices[i]);//第二次买,是在第一次卖掉的基础上购买buySecond = Math.max(buySecond, resultFirst - prices[i]);//第二次卖resultSecond = Math.max(resultSecond, buySecond+prices[i]);}return resultSecond;}