您的位置:首页 > 编程语言 > Java开发

123. Best Time to Buy and Sell Stock III(dp)

2016-09-20 17:22 330 查看
题目:

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).
同上,可以但是只能买两次
设状态f(i)表示区间[0,i-1]上的最大利润,设置状态g(i),表示区间[i,n-1]上最大利润。则最大利润为max{f(i)+g(i)};

public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length<2)return 0;
int max = 0;
int n = prices.length;
int[] l = new int
;
int[] r = new int
;
int min = prices[0];
for(int i=1;i<n;i++)
{
min = Math.min(prices[i], min);
l[i]=Math.max(prices[i]-min, l[i-1]);
}
int maxx = prices[n-1];
for(int i=n-2;i>=0;i--)
{
maxx= Math.max(prices[i], maxx);
r[i]=Math.max(maxx-prices[i], r[i+1]);
}

for(int i=0;i<n;i++)
{
max = Math.max(max, r[i]+l[i]);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java