Replay a day of stock movements
The warehouse log holds a day of movements for one part: positive for receipts, negative for picks. Replay them to get the closing figure.
- Stock can never go below zero. A pick larger than what is there empties the shelf and stops — it does not go negative.
- Because of that floor, the order matters: you cannot just add everything up.
stockAfterMoves(opening: int, moves: list<int>) → 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.
Where you start
int stockAfterMoves(int opening, std::vector<int> moves) {
}
Worked examples
| Call | Result |
|---|---|
stockAfterMoves(10, std::vector<int>{-3, 5, -4}) | 8 |
stockAfterMoves(10, std::vector<int>{-3, 5, -20}) | 0 |
stockAfterMoves(5, std::vector<int>{-10, 3}) | 3 |
stockAfterMoves(0, std::vector<int>{}) | 0 |
Hint
Apply one movement at a time and clamp at zero after each.
Reference solution in C++
int stockAfterMoves(int opening, std::vector<int> moves) {
int level = std::max(0, opening);
for (int m : moves) level = std::max(0, level + m);
return level;
}