首页 > 代码库 > Best Time To Sell Stock 3
Best Time To Sell Stock 3
题目
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,d[i]表示在i点之前卖掉第一次股票所得到的最大利润,这个狂野的想法很明显是要TLE的,最关键的问题是,进行了过多的重复计算,[i…n]和[i+1…n]的最大利润在prices[i+1] < prices[i]的时候是一样的
参考了别人的思路,分别算[0…i]的最大利润和[i…n]的最大利润,很明显[0…i]的最大利润的算法跟之前Stock1的解法是一样的,但是后面[i…n]的解法就更为暴力一点,从后往前扫,遇到最高的就记下来,最大利润就是当前max(highest - prices[i], maxproofit)。
代码
public class Solution { public int maxProfit(int[] prices) { if (prices.length == 0) { return 0; } // calculating [0...i] max profit int[] leftMaxProfit = new int[prices.length]; // calculating [i...n] max profit int[] rightMaxProfit = new int[prices.length]; leftMaxProfit[0] = 0; for (int i = 1; i < leftMaxProfit.length; i++) { int changes = prices[i] - prices[i - 1]; leftMaxProfit[i] = leftMaxProfit[i - 1] + changes < 0 ? 0 : leftMaxProfit[i - 1] + changes; } rightMaxProfit[0] = 0; int highest = prices[prices.length - 1]; int maxprofit = Integer.MIN_VALUE; int ret = 0; for (int i = rightMaxProfit.length - 1; i >= 1; i--) { int profit = highest - prices[i]; if (profit > maxprofit) maxprofit = profit; int finalprofit = maxprofit + leftMaxProfit[i]; if (finalprofit > ret) ret = finalprofit; if (prices[i] > highest) highest = prices[i]; } return ret; } }
Best Time To Sell Stock 3
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。