Best Time to Buy and Sell Stock IV

Given an array prices and an integer k, return the maximum profit you can achieve with at most k transactions. This is a richer version of the same DP state family and is ideal for comparing memoization with tabulation.

Input Format

k = maximum transactions, prices = stock prices by day

Output Format

maximum profit with at most k transactions

Constraints

  • 1 <= k <= 100; 1 <= prices.length <= 1000; 0 <= prices[i] <= 1000

Examples

Example 1:

Input:

k = 2
prices = [3,2,6,5,0,3]

Output:

7

Explanation:

Buy at 2 sell at 6, then buy at 0 sell at 3.

Example 2:

Input:

k = 2
prices = [2,4,1]

Output:

2

Explanation:

Only one profitable transaction exists.

Loading...
Best Time to Buy and Sell Stock IV