/123. Best Time to Buy and Sell Stock III

123. Best Time to Buy and Sell Stock III

Hard
Arrays53.3% acceptance

Given an integer array stock_prices where stock_prices[i] represents the price of a stock on day i, compute the maximum profit achievable by performing at most two buy-sell transactions. You cannot hold more than one stock at a time (i.e., you must sell before buying again). Return the maximum possible profit as an integer.

Example 1

Input: [2, 4, 1, 7, 5, 3, 6]

Output: 10

Explanation: Buy at 1, sell at 7 (profit 6). Buy at 3, sell at 6 (profit 3). Total profit: 6+3=9. But buying at 2, selling at 4 (profit 2), then buying at 1, selling at 7 (profit 6) gives 2+6=8. Best is buy at 1, sell at 7 (profit 6), buy at 3, sell at 6 (profit 3), total 9.

Example 2

Input: [8, 1, 2, 10, 4, 9]

Output: 14

Explanation: Buy at 1, sell at 10 (profit 9). Buy at 4, sell at 9 (profit 5). Total profit: 9+5=14.

Example 3

Input: [5, 4, 3, 2, 1]

Output: 0

Explanation: No profitable transaction possible.

Constraints

  • 1 <= len(stock_prices) <= 105
  • 0 <= stock_prices[i] <= 105
  • At most two buy-sell transactions allowed
  • Cannot hold multiple stocks simultaneously
Python (current runtime)

Case 1

Input: [1, 5, 2, 8, 3, 7]

Expected: 11

Case 2

Input: [10, 9, 8, 7, 6, 5]

Expected: 0

Case 3

Input: [3, 2, 6, 5, 0, 3]

Expected: 7

Case 4

Input: [1, 2, 4, 2, 5, 7, 2, 4, 9, 0]

Expected: 13