</>

122. Best Time to Buy and Sell Stock II

Medium
Greedy Time O(n) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Greedy
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryGiven a list of daily stock prices where you may buy and sell on any days (but must sell before buying again), find the maximum total profit you can collect across any number of transactions.

Approach
  • Key insight: The maximum profit equals the sum of every positive day-over-day price increase, because any upward run from valley to peak decomposes perfectly into consecutive single-day gains.
  • Iterate through the array once, accumulating prices[i] - prices[i-1] whenever it is positive.
  • This greedy strategy is provably optimal: capturing every upward step is equivalent to buying at every local valley and selling at every local peak, without needing to explicitly identify those turning points.
#include <vector>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        // Sum every positive consecutive difference.
        // This is equivalent to buying at each valley and selling at each peak.
        for (int i = 1; i < (int)prices.size(); ++i) {
            if (prices[i] > prices[i - 1])
                profit += prices[i] - prices[i - 1];
        }
        return profit;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit=0;
        int numOfDays=prices.size();
        
        if(numOfDays<2)
            return 0;

        int i=0;
        while(i<numOfDays){
            bool isBuyPoint=false;
            if(i==0)
                isBuyPoint=prices[i]<prices[i+1];
            else if(i==numOfDays-1)
                isBuyPoint=false; // we don't buy at the last time
            else 
                isBuyPoint = prices[i]<prices[i+1] && prices[i]<=prices[i-1];
                
            if(isBuyPoint){
                // find next local Max to sell
                int j=i+1; // j is sellPoint
                while(j<numOfDays-1){
                    if(prices[j]>prices[j+1])
                        break;
                    j++;
                }
                profit+=prices[j]-prices[i];
                i=j+1;
            }
            else
                i++;
        }

        return profit;
    }
};

// Time Complexity: O(n)
// Space Complexity: O(1)
Time O(n) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern