← DiffPush

Best Time to Buy and Sell Stock II

Standard Bar Dynamic Programming · DP on Stocks O(n) · O(1)

The Unlimited Charter Cycles

The broker's charter deal went unlimited: lock and release the depot fee as many times as desired, one share of cargo at a time, and even same-hour round trips are legal. Dispatch wants the maximum cumulative spread across the whole horizon. Every rise in the fee curve can now be captured piece by piece.

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

Output: Return the maximum total profit with unlimited buy-sell transactions, holding at most one unit at a time.

Constraints

Examples

Example 1

Input: {"prices":[7,1,5,3,6,4]}
Output: 7
Lock at 1, release at 5 (+4); lock at 3, release at 6 (+3) — total 7.

Example 2

Input: {"prices":[1,2,3,4,5]}
Output: 4
One long hold captures the entire climb: release at 5 after locking at 1.

Solve this in your browser →

Also on LeetCode ↗