Arrays

Stock Buy & Sell

LC
Practice this algorithm on LeetCode to reinforce your understanding.
Open Problem

Maximum Profit — One Transaction — O(n) time · O(1) space

What does it solve?

Given an array of stock prices where prices[i] is the price on day i, find the maximum profit from buying on one day and selling on a later day.

You can only buy before you sell — and you may complete at most one transaction. If no profit is possible, the answer is 0.

The core idea

// At each price, in this order:
maxProfit = max(maxProfit, price[i] - minPrice)
// "what if I sold today?"

minPrice = min(minPrice, price[i])
// track the cheapest buy point so far

Complexity

Time complexity
O(n)

One pass through the prices — each day visited exactly once.

Space complexity
O(1)

Only two variables needed: minimum price so far and maximum profit so far.


Examples & edge cases

Live animation
Current day Running min (cheapest so far) Best buy day Best sell day
Min price so far
—
—
Profit if sold today
—
—
Max profit (best)
—
—
Step
—
—
Select an example and press Play to start.
✓ Complete
Speed Medium

Step-by-step table

Step Day Price Min so far Profit today Max profit Action

C++ implementation

stock_profit.cpp
#include <bits/stdc++.h>
using namespace std;

// Returns {maxProfit, buyDay, sellDay}
tuple<int,int,int> maxProfit(vector<int>& prices) {
    int n = prices.size();
    int minPrice = prices[0];
    int minIdx = 0;
    int best = 0, buyDay = 0, sellDay = 0;

    for (int i = 1; i < n; i++) {
        // 1. What if we sold today, using the cheapest buy so far?
        int profitToday = prices[i] - minPrice;
        if (profitToday > best) {
            best = profitToday;
            buyDay = minIdx;
            sellDay = i;
        }

        // 2. Update the cheapest price seen so far
        if (prices[i] < minPrice) {
            minPrice = prices[i];
            minIdx = i;
        }
    }

    return {best, buyDay, sellDay};
}

int main() {
    vector<int> prices = {7, 1, 5, 3, 6, 4};

    auto [profit, buy, sell] = maxProfit(prices);

    cout << "Max profit: " << profit << "\n";
    cout << "Buy on day " << buy << ", sell on day " << sell << "\n";
    return 0;
}

My Notes

📝 Notes ✅

▼
===== -->