Drill

ProblemsPython › inventory

Replay a day of stock movements

mediuminventoryPython

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_after_moves(opening: int, moves: list<int>) → int

Solve it in the editor →

Where you start

def stock_after_moves(opening: int, moves: list[int]) -> int:
    

Worked examples

CallResult
stock_after_moves(10, [-3, 5, -4])8
stock_after_moves(10, [-3, 5, -20])0
stock_after_moves(5, [-10, 3])3
stock_after_moves(0, [])0

Hint

Apply one movement at a time and clamp at zero after each.

Reference solution in Python
def stock_after_moves(opening: int, moves: list[int]) -> int:
    level = max(0, opening)
    for m in moves:
        level = max(0, level + m)
    return level

The same problem in another language

More inventory problems in Python