LeetCode 123 Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝查询买家退货率 编辑:程序博客网 时间:2024/05/22 12:56

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).

front[i] 表示区间[0,i]的最大利润,back[i] 表示区间[i,n-1]的最大利润,n表示总天数。最大利润就是 max{ front[i]+back[i] }   0<=i<=n-1.

public int maxProfit3(int[] prices) {if (prices.length == 0) return 0;int minbuy = prices[0], profit = 0;int[] front = new int[prices.length];front[0] = 0;int[] back = new int[prices.length];back[prices.length - 1] = 0;for (int i = 1; i < prices.length; i++) {minbuy = Math.min(prices[i], minbuy);front[i] = Math.max(front[i - 1], prices[i] - minbuy);}for (int i = prices.length - 2, maxSell = prices[prices.length - 1]; i > 0; i--) {maxSell = Math.max(prices[i], maxSell);back[i] = Math.max(back[i - 1], maxSell - prices[i]);}for (int i = 0; i <prices.length ; i++) {profit = Math.max(front[i]+back[i],profit);}return profit;}

二刷

public int maxProfit3(int[] prices) {if (prices.length<2) return 0;int[] left=new int[prices.length];int res = 0, profit = 0;for (int i = 1; i <prices.length ; i++) {profit += prices[i] - prices[i - 1];if (profit < 0) profit = 0;res = Math.max(profit, res);left[i] = res;}int right = 0,max = res;profit = 0;for (int i = prices.length-2; i >0 ; i--) {profit += prices[i+1] - prices[i ];if (profit < 0) profit = 0;right = Math.max(profit, right);max = Math.max(max ,right+left[i]);}return max;}



0 0
原创粉丝点击