/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 non-overlapping buy-sell transactions. You may not hold more than one stock at a time (i.e., you must sell before buying again). Return the maximum 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). Then buy at 3, sell at 6 (profit 3). Total profit: 6+3=9. Alternatively, buy at 2, sell at 4 (profit 2), buy at 1, sell at 7 (profit 6), total profit: 2+6=8. Maximum is 9.

Example 2

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

Output: 15

Explanation: Buy at 1, sell at 10 (profit 9). Then buy at 3, sell at 9 (profit 6). Total profit: 9+6=15.

Example 3

Input: [5, 5, 5, 5, 5]

Output: 0

Explanation: No profit can be made.

Constraints

  • 1 <= len(stock_prices) <= 105
  • 0 <= stock_prices[i] <= 105
Python (current runtime)

Case 1

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

Expected: 14

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