[LeetCode] 123. 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 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).
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Thought process:
Iterate through the prices. Maintain variables to keep track of total profit at first buy, first sell, second buy and second sell.
- First buy: lowest price in prices.
- First sell: Highest profit after selling first stock.
- Second buy: Highest profit after buying second stock.
- Second sell: Highest profit after two transactions.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public int maxProfit(int[] prices) { int firstBuy = Integer.MAX_VALUE; int firstSell = 0; int secondBuy = Integer.MIN_VALUE; int secondSell = 0; for (int price : prices) { firstBuy = Math.min(firstBuy, price); firstSell = Math.max(firstSell, price - firstBuy); secondBuy = Math.max(secondBuy, firstSell - price); secondSell = Math.max(secondSell, secondBuy + price); } return secondSell; } } |
Time complexity: O(n).
Comments
Post a Comment