DSA Factory
Free Dynamic programming lessonsDynamic programming · Stage 9 · States · Step 3

Count what you have used

When a limit applies, put how much of it you have used into the table. About 15 minutes.

A limit on the number of trades

Now you may buy and sell, but only k complete trades in total, where a trade is one buy followed by one sell. With k of 1 you pick the best single pair of days. With a bigger k you want the k best ones that don't overlap.

The new difficulty is the limit itself. Before you buy on a given day, you need to know how many trades you have already used, so that number has to be part of what the table remembers.

A limit: becomes a column in the table: how much of it is used.

Two numbers for each trade

For each trade number j from 1 to k, keep two best profits. The first is the profit while you are holding the share you bought for trade j. The second is the profit once trade j is finished and you hold nothing.

Each day, buying for trade j starts from the finished profit of trade j − 1, minus today's price. Selling ends trade j by adding today's price to the holding profit. The answer is the finished profit for k trades.

Holding for trade j: comes from trade j − 1 being finished.
Finished trade j: comes from holding for trade j, then selling.
In code
hold = [-10**9] * (k + 1)
done = [0] * (k + 1)
Best profit with at most 2 trades · prices 2, 5, 1, 4, 3, 8
251438
holding for trade 1
-2
trade 1 done
0
holding for trade 2
-2
trade 2 done
0

Day 1, price 2. Buying for trade 1 costs 2, so holding is −2. Nothing is finished yet, so both finished rows stay at 0.

Move 1 of 6
Quick check

With at most 2 trades, you have finished your first trade with a profit of 4. Today's price is 5. What is the holding profit for trade 2 if you buy today?

  1. A−1
  2. B−5
  3. C9
Show the answer

−1. You start from the finished profit of trade 1, which is 4, and pay 5 to buy: 4 − 5 = −1.

Your problem

At most k trades

You are given an integer k and the price of a share on each day. You may complete at most k trades, where a trade is one buy followed by one sell, and you hold at most one share at a time. Return the largest total profit.

Example
k = 2, prices = [3, 2, 6, 5, 0, 3] → 7

0 ≤ k ≤ 100 · 0 ≤ days ≤ 300 · 1 ≤ price ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve