# 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;
}

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

## LeetCode Best Time to Buy and Sell Stock III && Best Time to Buy and Sell Stock IV

LeetCode这个买股票题，个人认为是出的比较好的，一共四个问题，其中3和4都是hard，在我看来，4的难度比3还是难了不少，因为他涉及到了dp的优化 这里就稍微再提一下第一问和第二问，第一问已经...

## LeetCode123—Best Time to Buy and Sell Stock III

LeetCode123—Best Time to Buy and Sell Stock III

## [LeetCode10]Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i. Design an...

## LeetCode | Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i. Design an a...

## Best Time to Buy and Sell Stock I && II && III

Best time to Buy and Sell Stock

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)