LeetCode 刷题【123. 买卖股票的最佳时机 III】
123. 买卖股票的最佳时机 III
自己做(歇菜)
class Solution {public int maxProfit(int[] prices) {int max = 0; //结果List<Integer> point = new ArrayList(); //存放峰值点int profit1 = 0; //第一支股票的当前利润int profit2 = 0; //第二支股票的当前利润int min_price1 = 0; //第一支股票的历史低点int min_price2 = 0; //第二支股票的历史低点//记录峰值点point.add(prices[0]); //第一个点for(int i = 1; i < prices.length - 1; i++){if(prices[i - 1] >= prices[i] && prices[i + 1] >= prices[i]) //峰值低点point.add(prices[i]);if(prices[i - 1] <= prices[i] && prices[i + 1] <= prices[i]) //峰值高点point.add(prices[i]);}point.add(prices[prices.length - 1]); //最后一个点for(int i = 0; i < point.size(); i++){ //第一支股票【相当于问题II】if(point.get(i) < point.get(min_price1)) //更新最低点min_price1 = i;if(point.get(i) - point.get(min_price1) > profit1){ //当前利润相比上次上涨,记录当前利润profit1 = point.get(i) - point.get(min_price1);if(i == point.size() - 1 && profit1 > max) //一直涨到最后,抛max = profit1;}else{ //当前利润出现下降,抛出,计算基于第一支股票在当前抛出后,第二支股票的最大利润min_price2 = i;for(int j = i + 1; j < point.size(); j++) //第二支股票【相当于问题I】if(point.get(j) < point.get(min_price2)) //更新最低点min_price2 = j;else if(point.get(j) - point.get(min_price2) > profit2) //更新第二支股票的最大利润profit2 = point.get(j) - point.get(min_price2);if(profit1 + profit2 > max) //找到第二支股票的最大利润max = profit1 + profit2;profit1 = 0; //初始化第一支股票的当前利润profit2 = 0; //初始化第二支股票的当前利润 } }return max;}
}
看题解
动态规划
官方代码
class Solution {public int maxProfit(int[] prices) {int n = prices.length;int buy1 = -prices[0], sell1 = 0; //开局负资产int buy2 = -prices[0], sell2 = 0; //买入负债for (int i = 1; i < n; ++i) {buy1 = Math.max(buy1, -prices[i]); //尝试买入第一支,buy代表当前持有的最低价sell1 = Math.max(sell1, buy1 + prices[i]); //尝试卖出第一支,看看比原来能不能卖更多buy2 = Math.max(buy2, sell1 - prices[i]); //尝试买入第二支sell2 = Math.max(sell2, buy2 + prices[i]); //尝试卖出第二支,得到的sell2即为总利润}return sell2;}
}