Drill

ProblemsPython › patterns

How long this price has held up

hardpatternsStacksArraysPython

A trading widget shows, for each day, how many days back the price has been no higher than it is today — today included.

price_run(prices: list<int>) → list<int>

Solve it in the editor →

Where you start

def price_run(prices: list[int]) -> list[int]:
    

Worked examples

CallResult
price_run([100, 80, 60, 70, 60, 75, 85])[1, 1, 1, 2, 1, 4, 6]
price_run([10, 20, 30])[1, 2, 3]
price_run([30, 20, 10])[1, 1, 1]
price_run([5, 5, 5])[1, 2, 3]

Hint

Rather than walking backwards each day, keep a stack of earlier days that were priced higher. Popping the ones that were not gives you the run in one pass.

Reference solution in Python
def price_run(prices: list[int]) -> list[int]:
    runs = []
    higher = []
    for i, price in enumerate(prices):
        while higher and prices[higher[-1]] <= price:
            higher.pop()
        runs.append(i + 1 if not higher else i - higher[-1])
        higher.append(i)
    return runs

The same problem in another language

More patterns problems in Python