您的位置:首页 > 其它

【LeetCode】123. Best Time to Buy and Sell Stock III

2018-03-16 18:18 706 查看

题目描述

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).

参考了题解的一位大神

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39653/2ms-Java-DP-Solution

代码如下

class Solution {
public int maxProfit(int[] prices) {

int firstBuy = Integer.MIN_VALUE;
int firstSell = 0;
int secondBuy = Integer.MIN_VALUE;
int secondSell = 0;

for(int curPrice:prices)
{
secondBuy = Math.max(secondBuy,firstSell-curPrice);
secondSell = Math.max(secondSell,secondBuy+curPrice);
firstBuy = Math.max(firstBuy,-curPrice);
firstSell = Math.max(firstSell,firstBuy+curPrice);

}
return secondSell;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: