Drill

ProblemsJava › patterns

How long this price has held up

hardpatternsStacksArraysJava

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

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> priceRun(List<Integer> prices) {
    
}

Worked examples

CallResult
priceRun(Main.<Integer>ls(100, 80, 60, 70, 60, 75, 85))Main.<Integer>ls(1, 1, 1, 2, 1, 4, 6)
priceRun(Main.<Integer>ls(10, 20, 30))Main.<Integer>ls(1, 2, 3)
priceRun(Main.<Integer>ls(30, 20, 10))Main.<Integer>ls(1, 1, 1)
priceRun(Main.<Integer>ls(5, 5, 5))Main.<Integer>ls(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 Java
List<Integer> priceRun(List<Integer> prices) {
    List<Integer> runs = new ArrayList<>();
    Deque<Integer> higher = new ArrayDeque<>();
    for (int i = 0; i < prices.size(); i++) {
        while (!higher.isEmpty() && prices.get(higher.peek()) <= prices.get(i)) higher.pop();
        runs.add(higher.isEmpty() ? i + 1 : i - higher.peek());
        higher.push(i);
    }
    return runs;
}

The same problem in another language

More patterns problems in Java