KatInterview

Best Profit from a Capped Number of Round-Trip Trades

Dynamic ProgrammingAuto-graded · 25 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingarraysstock-trading

Last updated

Maximize profit from daily share prices using at most k non-overlapping buy-then-sell trades, testing state-based dynamic programming and handling a trade limit that never binds.

You are given the daily price of a single stock as a list, where the entry at index i is the price on day i. You are also given a cap on the number of round trips you may make.

A round trip consists of buying one share on some day and selling that same share on a later day (or the same day, which earns nothing). Your goal is to choose trades that maximize total profit.

Implement max_profit_capped_trades(max_trades, prices) which returns the largest total profit achievable using at most max_trades round trips.

Rules

  • You may own at most one share at any moment. A share must be sold before another is bought.
  • A sale and the next purchase may take place on the same day.
  • You may make any number of round trips from zero up to max_trades. If no trade yields a gain, the answer is 0.
  • If max_trades is larger than the number of useful trades available, the unused allowance is simply ignored.

Input

  • max_trades: an integer, the maximum number of round trips allowed.
  • prices: a list of integers, the stock price on each day in order.

Output

An integer: the maximum total profit.

Constraints

  • 1 <= max_trades <= 100
  • 1 <= len(prices) <= 1000
  • 0 <= prices[i] <= 1000

Examples

Example 1

Input: max_profit_capped_trades(2, [3, 8, 2, 6, 1, 9])

Output: 13

Example 2

Input: max_profit_capped_trades(3, [3, 8, 2, 6, 1, 9])

Output: 17

Example 3

Input: max_profit_capped_trades(1, [4, 2, 7, 1, 3])

Output: 5

Hints

Hint 1

Think of the problem as a small state machine: on each day you are either holding a share or not, and you also care how many trades you have started or completed so far.

Hint 2

For each trade index j, keep the best cash balance while holding the j-th share, and the best cash balance after completing j sales. Each day updates these using the previous trade's completed balance and the current price.

Hint 3

If max_trades is at least half the number of days, the cap can never matter, since each profitable trade needs its own rising step separated from the next. Then the answer is just the sum of all positive day-to-day increases.