← DiffPush

Best Time to Buy and Sell Stock III

DiffPush Tier Dynamic Programming · DP on Stocks O(n) · O(1)

The Two-Shuttle Charter Cap

Fuel regulations cap the broker at two complete lock-release cycles for the season, one cargo unit at a time, never overlapping. Dispatch must decide when each of the two cycles opens and closes to maximize total spread. The planning system walks the fee curve while remembering how many cycles remain.

Input: An array prices where prices[i] is the fee on hour i.

Output: Return the maximum profit using at most two non-overlapping buy-sell transactions.

Constraints

Examples

Example 1

Input: {"prices":[3,3,5,0,0,3,1,4]}
Output: 6
(0 to 3) plus (1 to 4) — two cycles worth 3 each.

Example 2

Input: {"prices":[1,2,3,4,5]}
Output: 4
One cycle across the whole climb is already optimal; a second adds nothing.

Solve this in your browser →

Also on LeetCode ↗