Best Time to Buy and Sell Stock II
You are given an integer array prices where pricesi is the price of a stock on day i. You may buy and sell as many times as you like, but must sell before buying again. Return the maximum profit you can achieve. Use a greedy single pass: whenever the price rises from one day to the next, bank that gain immediately, as if you bought the day before and sold today.
Constraints
- 1 ≤ prices.length ≤ 3 × 104
- 0 ≤ pricesi ≤ 104
Example
prices = [7, 1, 5, 3, 6, 4]7Explanation Buy on day 1 (price 1), sell on day 2 (price 5), profit 4. Buy on day 3 (price 3), sell on day 4 (price 6), profit 3. Total 7.
Bank every day-over-day price increase
Day 1 price (1) is lower than day 0 (7) — nothing to capture.
What happens in this step
i = 1: prices[1] = 1, prices[0] = 7 1 < 7, so the price dropped. Nothing is captured — profit stays 0.
Steps to visualize
- Compare each day to the day before it.
- If the price rose, add the difference to the running profit.
- If the price dropped or stayed the same, there is nothing to capture.
- The sum of every positive difference equals the maximum achievable profit.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Day 1 price (1) is lower than day 0 (7) — nothing to capture.
What happens in this step
i = 1: prices[1] = 1, prices[0] = 7 1 < 7, so the price dropped. Nothing is captured — profit stays 0.
Solution
function maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
prices = [7, 1, 5, 3, 6, 4] | 7 | example from the docstring |
prices = [1, 2, 3, 4, 5] | 4 | prices rise every day, capture every increase |
prices = [7, 6, 4, 3, 1] | 0 | prices only fall, no profit possible |
prices = [5] | 0 | smallest valid input, a single day with no trade possible |
prices = [1, 5] | 4 | boundary case, one profitable trade |
prices = [5, 1] | 0 | boundary case, price drops so no trade is worth making |
prices = [3, 3, 3] | 0 | price never changes, nothing to capture |