Skip to the code
cf.
+50 XP

#509 Minimum Starting Battery for a Robot Tour

hard

A robot demo on a product page drives across a grid from the top-left cell to the bottom-right cell, moving one cell right or down at a time. Entering cell (r, c) changes its battery by grid[r][c]: positive values are chargers and negative values drain it. The start cell's value applies too.

The battery must be at least 1 at every moment, including right after entering the start cell and the end cell. Write minStartBattery(grid) that returns the smallest whole starting battery that lets the robot finish on some route.

Example 1

Input: grid = [[-3,5],[1,-4]]
Output: 4

Go right then down: 4 - 3 = 1, then 1 + 5 = 6, then 6 - 4 = 2. Going down first needs 7.

Example 2

Input: grid = [[2,-6],[-1,-2]]
Output: 2

Go down then right: 2 + 2 = 4, 4 - 1 = 3, 3 - 2 = 1.

Constraints

  • 1 <= rows, cols <= 200
  • -1000 <= grid[r][c] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).