Drill

ProblemsGo › inventory

Replay a day of stock movements

mediuminventoryArraysSimulationGo

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

Go 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

func stockAfterMoves(opening int, moves []int) int {
	
}

Worked examples

CallResult
stockAfterMoves(10, []int{-3, 5, -4})8
stockAfterMoves(10, []int{-3, 5, -20})0
stockAfterMoves(5, []int{-10, 3})3
stockAfterMoves(0, []int{})0

Hint

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

Reference solution in Go
func stockAfterMoves(opening int, moves []int) int {
	level := opening
	if level < 0 {
		level = 0
	}
	for _, m := range moves {
		level += m
		if level < 0 {
			level = 0
		}
	}
	return level
}

The same problem in another language

More inventory problems in Go