leetCode练习(123)

来源:互联网 发布:回到未来知乎 编辑:程序博客网 时间:2024/05/10 00:09

题目:Best Time to Buy and Sell Stock III          

难度:hard

问题描述:

Say you have an array for which the ith element is the price of a given stock on dayi.

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

解题思路:121题的拓展,121题只需要交易一次,顺序遍历一遍即可找到最大差。现在可以交易两次,我们容易想到,只要计算出所有prices[0,i]和prices[I,len-1]的和,找到最大的即可。对于prices[0,i] 同121题,只需遍历一次储存到firstProfit[]中即可。对于prices[I,len-1],我们可以从后往前遍历一遍即可。储存在secondProfit[]中,最后找到i使得firstProfit[I]+SecondProfit[I]最大就是最大贸易值。

代码如下:

public static int solution(int[] prices){if(prices==null||prices.length<2) return 0;int len=prices.length;int[]firstProfit=new int[len];int[]secondProfit=new int[len];int min=prices[0];for(int i=1;i<len;i++){min=Math.min(min, prices[i]);firstProfit[i]=Math.max(firstProfit[i-1], prices[i]-min);}int max=prices[len-1];for(int i=len-2;i>=0;i--){max=Math.max(max, prices[i]);secondProfit[i]=Math.max(secondProfit[i+1], max-prices[i]);}int res=0;for(int i=0;i<len;i++){res=Math.max(res, firstProfit[i]+secondProfit[i]);}return res;}

0 0
原创粉丝点击