[leetcode]123. Best Time to Buy and Sell Stock III(Java)

来源:互联网 发布:关闭端口的命令 编辑:程序博客网 时间:2024/06/05 16:06

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/#/description


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



package go.jacob.day715;public class Demo2 {public int maxProfit(int[] prices) {if (prices == null || prices.length < 2)return 0;// 四个变量分别表示经过当前操作以后的profitint firstBuy = Integer.MIN_VALUE, firstSell = 0;int secondBuy = Integer.MIN_VALUE, secondSell = 0;for (int curPrice : prices) {firstBuy = Math.max(firstBuy, -curPrice);firstSell = Math.max(firstSell, curPrice + firstBuy);secondBuy = Math.max(secondBuy, firstSell - curPrice);secondSell = Math.max(secondSell, secondBuy + curPrice);}return secondSell;}}


阅读全文
0 0
原创粉丝点击