beginner · arrays · greedy · running minimum

Buy once, sell once, profit most

Problem

Given a commodity's price on each day, choose one day to buy and a later day to sell to maximise profit. Return the best profit, or 0 if no profitable trade exists.

Constraints

  • 1 ≤ n ≤ 32
  • prices from 0 to 999

Examples

[7, 1, 5, 3, 6, 4] → 5 — Buy at 1, sell at 6.

[7, 6, 4] → 0

Show the solution

Running minimum

The best trade that sells on day i buys at the lowest price before i. Track that minimum as you go.

Why it is correct

When day i is processed, lowest is the minimum of prices[0..i), so prices[i] − lowest is the best profit for selling on day i; best takes the maximum over all days.

Complexity

Time O(n), extra space O(1). One pass, two comparisons per day.

For contrast: Try every pair buy < sell. That costs O(n²) time and O(1) space.

Edge cases

  • Falling prices: profit 0 (do not trade).
  • One day: 0.

Common mistakes

  • Updating lowest before computing today's profit (allows buying and selling on the same day, harmless here, but wrong in variants).
  • Taking the global minimum and maximum, which may be in the wrong order.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class StockProfit
{
    /// <summary>Best profit from one buy followed by one sell (0 if none). Precondition: at least one price. O(n).</summary>
    public static int Best(int[] prices)
    {
        int lowest = prices[0], best = 0;
        for (int i = 1; i < prices.Length; i++)
        {
            best = Math.Max(best, prices[i] - lowest); // sell today after the cheapest earlier day
            lowest = Math.Min(lowest, prices[i]);
        }
        return best;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/StockProfit.cs

from collections.abc import Sequence
 
 
def best(prices: Sequence[int]) -> int:
    """Best profit from one buy followed by one sell (0 if none). Precondition: at least one price. O(n)."""
    lowest, result = prices[0], 0
    for price in prices[1:]:
        result = max(result, price - lowest)  # sell today after the cheapest earlier day
        lowest = min(lowest, price)
    return result

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/stock_profit.py

package dev.bekadan.dsa.problems;
 
public final class StockProfit {
    private StockProfit() {
    }
 
    /** Best profit from one buy followed by one sell (0 if none). Precondition: at least one price. O(n). */
    public static int best(int[] prices) {
        int lowest = prices[0], best = 0;
        for (int i = 1; i < prices.length; i++) {
            best = Math.max(best, prices[i] - lowest); // sell today after the cheapest earlier day
            lowest = Math.min(lowest, prices[i]);
        }
        return best;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/StockProfit.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <span>
 
namespace bekadan::dsa::problems {
 
// Best profit from one buy followed by one sell (0 if none). Precondition: at least one price. O(n).
inline int stock_profit(std::span<const int> prices) {
    int lowest = prices[0], best = 0;
    for (std::size_t i = 1; i < prices.size(); ++i) {
        best = std::max(best, prices[i] - lowest);  // sell today after the cheapest earlier day
        lowest = std::min(lowest, prices[i]);
    }
    return best;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/stock_profit.hpp