leetCode 123. Best Time to Buy and Sell Stock III

来源:互联网 发布:form表单转json 编辑:程序博客网 时间:2024/05/14 02:31

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

给一个一维数组,代表每天股票价格,找出交易两次最大的获利选择
例如
Input: [7, 1, 5, 3, 6, 4]
最大为7,即【1,5】=4,【3,6】=3

用dp1[i]记录maxprofit[0,i],
用dp2[i]记录maxprofit[i,len-1]
输出就是max(dp1[i]+dp2[i]), i=0~n-1

public static int maxProfit(int[] prices) {         int len = prices.length;         if(len<=1)return 0;         int max=0;         int dp1[] = new int[len];           int curmin= prices[0];           for(int i=1;i<len;i++){               max = max < prices[i] - curmin ? prices[i] - curmin : max;               curmin =  prices[i] < curmin ?  prices[i] : curmin;               dp1[i] = max;           }           int curmax= prices[len-1];           max=0;           int dp2[] = new int[len];           for(int i=len-1;i>=0;i--){               max = max < curmax-prices[i] ? curmax-prices[i]  : max;               curmax =  prices[i] > curmax ?  prices[i] : curmax;               dp2[i] = max;           }           max=0;           for(int i=len-1;i>0;i--){               max = max < dp1[i]+dp2[i] ? dp1[i]+dp2[i]  : max;           }    return max;    }
阅读全文
0 0
原创粉丝点击