Problems › JavaScript › inventory
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
Where you start
function stockAfterMoves(opening, moves) {
}
Worked examples
| Call | Result |
|---|---|
stockAfterMoves(10, [-3,5,-4]) | 8 |
stockAfterMoves(10, [-3,5,-20]) | 0 |
stockAfterMoves(5, [-10,3]) | 3 |
stockAfterMoves(0, []) | 0 |
Hint
Apply one movement at a time and clamp at zero after each.
Reference solution in JavaScript
function stockAfterMoves(opening, moves) {
let level = Math.max(0, opening);
for (const m of moves) level = Math.max(0, level + m);
return level;
}