# leetcode中的股票问题（3）

## 原题

Say you have an array for which the ith$i^{th}$ element is the price of a given stock on day i$i$.
Design an algorithm to find the maximum profit. You may complete at most two transactions.

## 代码

public int maxProfit(int[] prices) {

if(prices.length < 2)
{
return 0;
}
//left to right scan
int[] left = new int[prices.length];
//right to left scan
int[] right = new int[prices.length];

//for index i, find the max profit can be made
//if at most one transaction can be completed before day i
int minTag = prices[0];
left[0] = 0;
for(int i = 1; i < prices.length - 1; i++)
{
left[i] = Math.max(left[i - 1], prices[i] - minTag);
minTag = Math.min(minTag,prices[i]);
}

//for index i, find the max profit can be made
//if at most one transaction can be completed after day i
int maxTag = prices[prices.length - 1];
right[prices.length - 1] = 0;
for(int i = prices.length - 2; i >= 0; i--)
{
right[i] = Math.max(right[i + 1], maxTag - prices[i]);
maxTag = Math.max(maxTag,prices[i]);
}

int profit = 0;
for(int i = 0; i < prices.length; i++)
{
//find the maximun profit
if(left[i] + right[i] > profit)
{
profit = left[i] + right[i];
}
}
return profit;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Best Time to Buy and Sell Stock III 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)