Big O Gym › Problem

Big O Practice: Best Time Buy Sell Stock

Time and space complexity practice in Python and JavaScript. Concept tested: running minimum with running best.

def max_profit(prices):
    min_price = float('inf')
    best = 0
    for p in prices:
        if p < min_price:
            min_price = p
        elif p - min_price > best:
            best = p - min_price
    return best

Variables

  • n - length of the prices array

Explanation

A single pass tracking the running minimum and the best gap so far - **O(n)** time, **O(1)** space. The brute-force "all pairs" version is O(n²); recognizing that you only need the min-so-far on the left is the trick.

More Big O practice problems · Today's daily problem