KatInterview

Maximum Ore Haul on a Climb-and-Step Grid Route

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggridmatrix

Last updated

Grid dynamic programming: find the route with the largest sum from the bottom-left to the top-right cell when only moving up or right.

Maximum Ore Haul

A miner explores a rectangular map stored as a 2D list of integers field with m rows and n columns. The value field[r][c] is the amount of ore lying in the cell at row r, column c. Row 0 is the top row and column 0 is the leftmost column.

The miner begins in the bottom-left cell, (m - 1, 0), and must finish in the top-right cell, (0, n - 1). From any cell (r, c) the miner may take one of two steps:

  • Up to (r - 1, c)
  • Right to (r, c + 1)

Every cell the miner stands on, including the starting cell and the final cell, has its ore collected in full. Because every step goes up or right, no cell can be visited twice.

Return the largest total amount of ore that can be collected along any valid route from the start cell to the finish cell.

Constraints

  • m == len(field)
  • n == len(field[0])
  • 1 <= m, n <= 1000
  • 0 <= field[r][c] <= 10^5
  • If the grid is 1 x 1, the start and finish are the same cell, and the answer is that cell's value.
  • If the grid has a single row or a single column, exactly one route exists.

Examples

Example 1

Input: max_ore_haul([[0, 2, 5], [1, 1, 3], [2, 1, 1]])

Output: 12

Example 2

Input: max_ore_haul([[1, 3], [2, 4]])

Output: 9

Example 3

Input: max_ore_haul([[7]])

Output: 7

Hints

Hint 1

Every route enters a cell from only one of two neighbors: the cell directly below it or the cell directly to its left.

Hint 2

Define best[r][c] as the maximum ore collectable on a route from the start that ends at (r, c), and express it using best of the two possible predecessors.

Hint 3

Process rows from the bottom to the top and columns left to right so both predecessors are ready. A single array of length n is enough since each row only needs the row beneath it.