Best Time to Buy and Sell Stock IV
HardTop Interview 150 2-D Dynamic ProgrammingPubMaticProblem
You are given an integer k and a list prices with one stock price per day.
You may complete at most k buy-then-sell trades. You can hold only one share at a time, so you must sell before you buy again.
Return the largest total profit you can make. Return 0 if no trade makes money.
Constraints
- 1 ≤ k ≤ 100
- 1 ≤ prices.length ≤ 1000
- 0 ≤ prices[i] ≤ 1000
Examples: pick one to animate
Solutions
Time: For each of the n days we update k buy values and k sell values in constant time. When k is at least n / 2 a single O(n) pass is used instead.
Space: Two arrays of k + 1 numbers. The shortcut for large k uses only one number.
For each trade number t keep buy[t], the best balance while holding the share of trade
t, and sell[t], the best balance after finishing t trades. Each day, a buy is the
better of keeping the old value or paying today's price out of sell[t - 1], and a sell is the better of
keeping the old value or adding today's price to buy[t]. If k is at least half the number of
days, the limit can never bind, so simply collect every price rise.