Skip to main content
Back to problems
Leetcode
Medium
Arrays
Greedy
Dynamic Programming
Amazon
Google
Best Time To Buy And Sell Stock Ii

Maximize profit from a stock price array by making as many buy-sell transactions as you want, without holding more than one share at a time.

Acceptance 100%
Problem Statement

Problem

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

You may complete as many transactions as you like, but you must follow these rules:

  • You can hold at most one share at a time.
  • To complete a transaction, you must buy before you sell.
  • You may buy and sell on different days only.

Return the maximum profit you can achieve.

Intuition target

The key is to decide which price increases are worth capturing across consecutive days.

Input Format

  • A single integer array prices of length n.
  • Each prices[i] is the stock price on day i.

Output Format

  • Return one integer: the maximum achievable profit.

Constraints

  • 1 <= n <= $10^{5}$
  • 0 <= prices[i] <= $10^{4}$
  • You may perform any number of transactions.
  • You cannot hold more than one share at any time.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

7

Explanation

Buy at 1 and sell at 5 for profit 4, then buy at 3 and sell at 6 for profit 3. Total profit = 7.

Example 2

Input

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

Output

4

Explanation

The best strategy is to capture every upward move: (2-1) + (3-2) + (4-3) + (5-4) = 4.

Show 1 more example

Example 3

Input

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

Output

0

Explanation

Prices never rise, so no transaction is profitable.

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.