Drill

ProblemsTypeScript › inventory

Replay a day of stock movements

mediuminventoryTypeScript

The warehouse log holds a day of movements for one part: positive for receipts, negative for picks. Replay them to get the closing figure.

stockAfterMoves(opening: int, moves: list<int>) → int

Solve it in the editor →

Where you start

function stockAfterMoves(opening: number, moves: number[]): number {
  
}

Worked examples

CallResult
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 TypeScript
function stockAfterMoves(opening: number, moves: number[]): number {
  let level = Math.max(0, opening);
  for (const m of moves) level = Math.max(0, level + m);
  return level;
}

The same problem in another language

More inventory problems in TypeScript