您的位置:首页 > 其它

【数组&DP】Best Time to Buy and Sell Stock III

2014-04-06 21:04 337 查看
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).
题意:最多只能买卖两次
解法:dp,d[i]表示0...i和i...n-1这两个区域中利润最大值

所以,遍历两次,分别求出0到i,i到n-1的最大值

public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len == 0 || len==1) return 0;

int d[] = new int[len];
int res = 0;
int minVal = prices[0];//当前最小元素值
int max = 0;//最大利润
d[0] = 0;
for(int i=1; i<len; i++){
minVal = Math.min(minVal, prices[i]);
max = Math.max(max, prices[i]-minVal);
d[i] = max;
}

int maxVal = prices[len-1];//当前最大元素值
max = 0;//最大利润值
res = d[len-1];
for(int i=len-2; i>=0; i--){
maxVal = Math.max(maxVal, prices[i]);
max = Math.max(max, maxVal - prices[i]);
d[i] += max;
res = Math.max(d[i], res);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: