Minimum Starting Health to Cross a Grid Moving Only Right or Down
Company: Goldman Sachs
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
Overview: Given a grid of damage and healing values, find the smallest positive starting health that lets a traveler move only right or down from the top-left cell to the bottom-right cell without health ever dropping below one. It tests dynamic programming over grid paths and precise handling of the first and last cells.
Constraints
- 1 <= m <= 200 and 1 <= n <= 200, where m = len(grid) and n = len(grid[0]); every row has length n.
- Every cell is an integer in [-1000, 1000].
- The starting health is a positive integer, and after each cell your health must be at least 1; health has no upper limit.
- The answer is at most 1 + 399 * 1000 = 399001.
- No value in this problem can exceed 2^31 - 1: the answer and every intermediate requirement fit in a signed 32-bit integer, so Java may use int and C++ may use int (long / long long are not needed).
Examples
Input: ([[-3, 5], [-10, 1]],)
Expected Output: 4
Explanation: Source example 1: right then down visits -3, 5, 1, so health goes 4 -> 1 -> 6 -> 7. Going down first would require 14.
Input: ([[2, -4, 1], [-1, -2, 3]],)
Expected Output: 2
Explanation: Source example 2: down, right, right visits 2, -1, -2, 3, so health goes 2 -> 4 -> 3 -> 1 -> 4. Each other path needs at least 3.
Hints
- Validity is a property of every prefix of a path, not of its total: check the health after each cell, including the top-left and bottom-right ones, and notice that a path with a large total can still be fatal early.
- Two different ways of reaching the same cell can be compared if you know a single number about that cell. Ask what you would need to know at a cell in order to decide the rest of the trip, rather than what you have accumulated getting there.
- Because health must be at least 1 after every cell, any requirement you compute for a cell is itself never less than 1 — a big heal cannot lower it past that floor.