← DSA practice

Best Time to Buy and Sell Stock

EasyArrays · GreedyO(n) time · O(1) space

The problem

You are given daily prices. Choose one day to buy and a later day to sell to maximise profit. Return the maximum profit, or 0 if no profit is possible.

[7, 1, 5, 3, 6, 4]  →  5   (buy at 1, sell at 6)
[7, 6, 4, 3, 1]     →  0
Stuck? Open one hint

Walk forward once. At today's price, what single number from the past is enough to compute the best sale today?

Show the worked solution

You do not need every pair. At each day, the best possible sale today uses the cheapest price seen so far.

So track two things while walking: the minimum price so far, and the best profit so far. Update the minimum after computing today's profit.

This is the pattern behind a whole family of questions — "best so far while scanning once". Naming the pattern scores well.

fun maxProfit(prices: IntArray): Int {
    var minPrice = Int.MAX_VALUE
    var best = 0
    for (price in prices) {
        if (price < minPrice) minPrice = price
        else best = maxOf(best, price - minPrice)
    }
    return best
}

O(n) time · O(1) space