ExamAdda Logo

Best Time to Buy and Sell Stock III

Easy

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

You may complete at most two 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

n = 8
prices = [3, 3, 5, 0, 0, 3, 1, 4]

Output

6

Explanation

The maximum profit can be achieved with two transactions:

Buy at 3 → Sell at 5 = 2
Buy at 0 → Sell at 4 = 4

 

Total profit:

2 + 4 = 6

 

Example 2

Input

n = 5
prices = [1, 2, 3, 4, 5]

Output

n = 5
prices = [1, 2, 3, 4, 5]

Explanation

The best strategy is one transaction:

Buy at 1 → Sell at 5

 

Profit:

5 - 1 = 4

 

Using a second transaction cannot increase the profit.

Constraints

1 <= prices.length <= 10^5
0 <= prices[i] <= 10^5
You may complete at most two transactions.
You must sell before buying again.

Hints:

Hint 1

Think about the four important states:

  1. First buy
  2. First sell
  3. Second buy
  4. Second sell
Hint 2

Maintain the best value for each state while traversing the prices.

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