Drill

ProblemsC++ › patterns

How long this price has held up

hardpatternsStacksArraysC++

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>

C++ 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

std::vector<int> priceRun(std::vector<int> prices) {
    
}

Worked examples

CallResult
priceRun(std::vector<int>{100, 80, 60, 70, 60, 75, 85})std::vector<int>{1, 1, 1, 2, 1, 4, 6}
priceRun(std::vector<int>{10, 20, 30})std::vector<int>{1, 2, 3}
priceRun(std::vector<int>{30, 20, 10})std::vector<int>{1, 1, 1}
priceRun(std::vector<int>{5, 5, 5})std::vector<int>{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 C++
std::vector<int> priceRun(std::vector<int> prices) {
    std::vector<int> runs;
    std::vector<int> higher;
    for (int i = 0; i < static_cast<int>(prices.size()); i++) {
        while (!higher.empty() && prices[higher.back()] <= prices[i]) higher.pop_back();
        runs.push_back(higher.empty() ? i + 1 : i - higher.back());
        higher.push_back(i);
    }
    return runs;
}

The same problem in another language

More patterns problems in C++