</>

121. Best Time to Buy and Sell Stock

Easy NeetCode 150
Sliding Window Time O(n) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Sliding Window
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryGiven a list of daily stock prices, find the maximum profit achievable by buying on one day and selling on a strictly later day (at most one transaction), returning 0 if no profit is possible.

Approach
  • Maintain two running values: the minimum price seen so far (best buy candidate) and the maximum profit seen so far.
  • For each price, compute the profit if we sold today (current price minus running minimum), then update the maximum profit.
  • Update the running minimum after the profit check so we never sell before we buy.
  • A single left-to-right pass is sufficient because the optimal buy day always precedes the optimal sell day.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice = prices[0]; // cheapest buy price seen so far
        int maxProf  = 0;         // best profit seen so far

        for (int price : prices) {
            // Would selling today beat our current best?
            maxProf  = max(maxProf, price - minPrice);
            // Track the lowest price available to buy
            minPrice = min(minPrice, price);
        }

        return maxProf;
    }
};
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 curMaxProfit=0;
        int curMinPrice=prices[0];

        for(int price: prices){
            curMaxProfit=std::max(curMaxProfit, price-curMinPrice);
            curMinPrice=std::min(curMinPrice, price);
        }

        return curMaxProfit;
    }
};

// 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