买卖股票的最佳时期
题目:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
1)创建一个和给定数组相同长度的新的数组profit,并将其中的元素全部初始化为0。
2) 从右向左遍历更新profit[i] 的值,使得其保存price[i…n-1] 中的最大利润值。
3) 从左向右遍历更新,使得其保存price[0,i ] 中的最大利润值
4) Return profit[n-1]
public int maxProfit(int[] prices)
{
if(prices.length>0)
{
int[] profit=new int[prices.length];
for (int i=0; i<profit.length; i++)
profit[i] = 0;
int max_prices = prices[prices.length-1];
for (int i=prices.length-2;i>=0;i--)
{
if (prices[i] > max_prices)
max_prices = prices[i];
profit[i] = Math.max(profit[i+1], max_prices-prices[i]);
}
int min_prices = prices[0];
for (int i=1; i<prices.length; i++)
{
if (prices[i] < min_prices)
min_prices = prices[i];
profit[i] = Math.max(profit[i-1], profit[i] +
(prices[i]-min_prices) );
}
int result = profit[profit.length-1];
return result;
}