Skip to main content
Back to problems
Leetcode
Medium
Arrays
Dynamic Programming
Google
Microsoft
Best Time To Buy And Sell Stock III

Maximize profit from stock prices with at most two buy-sell transactions.

Acceptance 0%
Problem Statement

Problem

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

You may complete at most two transactions. A transaction consists of one buy followed by one sell. You must sell the stock before you buy again.

Return the maximum profit you can achieve.

If no profit is possible, return 0.

Explanation

You are allowed to choose up to two non-overlapping buy-sell pairs. The goal is to maximize total profit across both transactions.

Input Format

  • An integer array prices where each element is the stock price on that day.

Output Format

  • Return a single integer: the maximum achievable profit with at most two transactions.

Constraints

  • 1 <= prices.length
  • Prices are non-negative integers.
  • You may perform at most two transactions.
  • You must sell before buying again.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

6

Explanation

Buy at 0, sell at 3 for profit 3, then buy at 1 and sell at 4 for profit 3. Total profit is 6.

Example 2

Input

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

Output

4

Explanation

Buy at 1 and sell at 5 for profit 4. Using only one transaction is optimal here.

Show 1 more example

Example 3

Input

prices = [7,6,4,3,1]

Output

0

Explanation

The price only decreases, so no profitable transaction exists.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.