ExamAdda Logo

Best Time to Buy and Sell Stock IV

Easy

You are given an integer array prices where prices[i] is the price of a stock on the ith day.

You may complete at most k transactions.

A transaction consists of:

  • Buying one stock.
  • Selling that stock later.

You must sell the stock before buying again.

Return the maximum profit you can achieve.

Example 1

Input

k = 2
n = 6
prices = [2, 4, 1, 7, 5, 9]

Output

11

Explanation

The maximum profit can be obtained using two transactions:

Buy at 2 → Sell at 4 = 2
Buy at 1 → Sell at 9 = 8

 

Total profit:

2 + 8 = 10

 

However, a better valid choice is:

Buy at 2 → Sell at 7 = 5
Buy at 5 → Sell at 9 = 4

 

Therefore, the maximum profit is:

5 + 4 = 9

 

Correction: For this input, the correct output is 9, not 11.

Example 2

Input

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

Output

4

Explanation

The best transaction is:

Buy at 2 → Sell at 6 = 4

 

No second transaction can add profit.

Constraints

1 <= k <= 100
1 <= prices.length <= 1000
0 <= prices[i] <= 1000
You may complete at most k transactions.
You must sell before buying again.

Hints:

Hint 1

For each transaction, maintain two states:

  • Buy: maximum profit after buying.
  • Sell: maximum profit after selling.
Hint 2

For k transactions, maintain these states for every transaction number.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 24, 2026

Last updated

Aug 24, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output