Best Time to Buy and Sell Stock II

MediumArrays · Greedy🧩 Array ManipulationLeetCode #122 ↗Updated

Problem

prices[i] is a stock's price on day i. You may trade as many times as you like, but you can hold at most one share at a time (buying and selling on the same day is allowed). Return the maximum total profit.
Input[7,1,5,3,6,4]Output7
Input[1,2,3,4,5]Output4
Input[7,6,4,3,1]Output0

1 ≤ n ≤ 3·104  ·  0 ≤ prices[i] ≤ 104

Try it yourself

Java
class Solution {
    public int maxProfit(int[] prices) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Any profitable hold from day a to day b equals the sum of the daily changes between them. So just collect every positive day-to-day rise — nothing else can beat it.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceRecursion — Try Every Decision

Time O(2n)Space O(n)

On each day you either do nothing, or act (buy if empty-handed, sell if holding). Recursively explore both branches and keep the better profit. Exhaustive, so obviously correct.

Java
public int maxProfit(int[] prices) {
    return solve(prices, 0, false);
}
private int solve(int[] p, int i, boolean holding) {
    if (i == p.length) return 0;
    int skip = solve(p, i + 1, holding);
    int act = holding ? p[i] + solve(p, i + 1, false)   // sell
                      : -p[i] + solve(p, i + 1, true);  // buy
    return Math.max(skip, act);
}

Explores 2n paths — only usable for tiny inputs.

At a glance

LevelApproachTimeSpace
Brute ForceRecursion — Try Every DecisionO(2n)O(n)
BetterDP — Hold / Free StatesO(n)O(n)
OptimalGreedy — Sum Positive DifferencesO(n)O(1)
Common pitfalls
  • Solving Stock I (single trade) by mistake — here trades are unlimited.
  • Holding two shares at once in the recursion — buy only when not holding.
  • Returning hold[n-1] instead of free[n-1] — ending with a share is never better.
Interview tips
  • Prove the greedy: any span's profit = sum of its daily deltas.
  • Present the DP first if the interviewer hints at fee/cooldown variants.
  • Mention the DP rolls into two variables → O(1) space as well.
Pattern
Greedy on local gains → when the total decomposes into independent non-negative pieces.
My notes saved in this browser