Loading...
Loading...
1 <= prices.length <= 10^5 0 <= prices[i] <= 10^5
You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by making at most two transactions (a transaction consists of buying then selling one share of stock).
Important rules:
Return the maximum profit you can achieve. If no profit is possible, return 0.
Input: An array of integers prices of length n.
Output: A single integer representing the maximum profit.
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price=0), sell on day 6 (price=3), profit=3. Then buy on day 7 (price=1), sell on day 8 (price=4), profit=3. Total profit = 3+3 = 6.
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price=1), sell on day 5 (price=5), profit=4. Only one transaction is needed. Total profit = 4.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Prices only go down, so no profitable transaction is possible. Return 0.
buy1: minimum cost after the first buysell1: maximum profit after the first sellbuy2: maximum profit after the second buy (profit from sell1 minus current price)sell2: maximum profit after the second sell