Grid Game

Two robots cross a two-row grid of points: choose the first robot's path so the second collects as little as possible.

You are given a grid of points with two rows and n columns, as a 2D array grid, where grid[r][c] is the number of points in row r and column c. Two robots start in the top-left cell and must end in the bottom-right cell. Each move goes one cell to the right or one cell down.

The first robot makes its whole trip first. It collects the points on every cell of its path, and those cells drop to 0. Then the second robot makes its trip and collects what is left on its path. The first robot wants the second to collect as few points as possible, and the second wants as many as possible. Return the points the second robot collects when both play their best.

Example 1
Input: grid = [[2, 5, 4], [1, 5, 1]]
Output: 4
Example 2
Input: grid = [[3, 3, 1], [8, 5, 2]]
Output: 4
Example 3
Input: grid = [[1, 3, 1, 15], [1, 3, 3, 1]]
Output: 7
Solution

The Idea

Picture two people crossing a floor of tiles, one after the other, with coins lying on the tiles. The first person picks up every coin they step on, and the second gets only what is left. The twist here is that the first person does not care about their own coins. They only want to leave the second person as little as possible.

Take Example 1. The top row holds 2, 5 and 4, and the bottom row holds 1, 5 and 1. A robot starts on the 2 in the top-left corner and must end on the 1 in the bottom-right corner. With only right and down moves and only two rows, it goes down exactly once. So a whole path is settled by one choice: the column where the robot goes down. A grid with n columns has only n possible paths.

Look at the picture below, where the columns are numbered from 0. On the left, the first robot goes down in column 1. It collects 2 + 5 + 5 + 1 = 13, and those four cells become 0. On the right is the grid the second robot sees. Only two cells still have points: the 4 in the top right and the 1 in the bottom left.

Example 1. Left: the first robot moves right along the top, goes down in column 1 and moves right along the bottom, collecting 13. Right: the grid after it, where only the top right cell, 4, and the bottom left cell, 1, still have points. The second robot can reach only one of them and takes 4.

Which of the two can the second robot get? To reach the 4, it must stay on the top row past column 1, so it can go down only in the last column, and by then the 1 in column 0 is behind it. To reach the 1, it must go down in column 0, and then the top row is out of reach. So it gets the top right or the bottom left, never both, and it takes the bigger one: 4.

Was column 1 the best choice for the first robot? Going down in column 0 leaves the 5 and the 4 on the top row, so the second robot gets 9. Going down in column 2 leaves the 1 and the 5 on the bottom row, so it gets 6. Column 1 leaves only 4, the smallest of the three, and 4 is the answer.

The same holds for any grid. If the first robot goes down in column d, what is left is the top row to the right of column d and the bottom row to the left of it. Call their sums the top right and the bottom left. The second robot takes the larger of the two, and the first robot picks the column where that larger sum is smallest.

Solution Approach

Turning that idea into code means settling three things: what the first robot aims for, how to get the two sums for every column quickly, and which type can hold the sums.

What the first robot aims for

Why not let the first robot simply collect as many points as it can? Fewer points left sounds like fewer points for the second robot, but where the leftovers lie matters too. Take the grid [[1, 5, 6], [6, 6, 1]]. Going down in column 0 gives the first robot its biggest total, 1 + 6 + 6 + 1 = 14. That leaves 5 + 6 = 11 on the top row, all of it reachable.

Going down in column 1 collects only 13, but leaves a 6 in the top right and a 6 in the bottom left. The second robot can take just one of them, so it gets 6. The first robot therefore looks at what it leaves behind, not at what it takes.

Summing the leftovers for each column

How do we get the top right and the bottom left for every column? The simple way adds up both parts again for each column. That is up to n additions for each of the n columns, about n² steps, or about 2.5 billion for a grid 50,000 columns wide.

Neighbouring columns share almost all of their sums, though. When the first robot goes down one column further right, the top right loses one cell and the bottom left gains one. So two running totals are enough: topRight starts as the sum of the whole top row, and bottomLeft starts at 0.

For each column, first subtract that column's top cell from topRight, then compare the two totals, and only then add the column's bottom cell to bottomLeft. That order keeps the column the first robot walks down out of both sums. A sum over the start of a row is called a prefix sum, and one over its end a suffix sum. So bottomLeft is a prefix sum of the bottom row and topRight a suffix sum of the top row. Here they are kept up to date as the loop moves from column to column, so no arrays of sums are needed.

Holding the sums without overflow

Can the sums get too big? A Java int holds values up to 2,147,483,647, about 2.1 billion. A top row of 50,000 cells worth 100,000 points each adds up to 5 billion, which does not fit. An int that goes past its largest value continues from the most negative values, which is called overflow. Keeping the totals and the answer in long, which holds far bigger values, avoids it.

Java Solution

The method gridGame works in these steps:

  1. First, add up the whole top row into topRight, a long. Start bottomLeft at 0, and best, the smallest answer so far, at Long.MAX_VALUE, so the first column's result always replaces it.
  2. Then loop over the columns with down, the column where the first robot goes down. Subtract grid[0][down] from topRight, so it holds only the top cells to the right of down.
  3. The second robot takes the larger total, Math.max(topRight, bottomLeft), saved in second. Keep the smaller of best and second in best.
  4. Add grid[1][down] to bottomLeft, so it is ready for the next column.
  5. When the loop is done, return best.

The main method runs the three examples, the grid [[1, 5, 6], [6, 6, 1]] from above, a grid with one column, and two rows of 50,000 cells worth 100,000 points each.

Java
import java.util.Arrays;

public class GridGame {

    public static long gridGame(int[][] grid) {
        int n = grid[0].length;
        long topRight = 0;
        for (int v : grid[0]) {
            topRight += v;                     // the whole top row, to start
        }
        long bottomLeft = 0;
        long best = Long.MAX_VALUE;
        for (int down = 0; down < n; down++) { // the first robot goes down here
            topRight -= grid[0][down];         // now only the cells right of down
            long second = Math.max(topRight, bottomLeft);
            best = Math.min(best, second);
            bottomLeft += grid[1][down];       // ready for the next column
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(gridGame(new int[][] {{2, 5, 4}, {1, 5, 1}}));
        System.out.println(gridGame(new int[][] {{3, 3, 1}, {8, 5, 2}}));
        System.out.println(gridGame(new int[][] {{1, 3, 1, 15}, {1, 3, 3, 1}}));
        System.out.println(gridGame(new int[][] {{1, 5, 6}, {6, 6, 1}}));
        System.out.println(gridGame(new int[][] {{5}, {7}}));
        int[] row = new int[50000];
        Arrays.fill(row, 100000);
        System.out.println(gridGame(new int[][] {row, row}));
    }
}

Running it prints:

Output
4
4
7
6
0
2500000000

The first three lines, 4, 4 and 7, answer the three examples. The fourth line comes from the grid [[1, 5, 6], [6, 6, 1]]. The code finds 6, while a first robot that grabs the most points would leave 11. The fifth line is 0, because with one column the first robot's only path covers both cells.

Look at the last line, the big grid. The answer, 2,500,000,000, is itself too big for an int. With every total kept in int instead, the same grid gives -1,794,967,296, and the top row's sum alone overflows to 705,032,704.

The original implementation, GridGame.java, is on GitHub.

Complexity

The work is one pass to add up the top row, then one pass over the columns.

  • Time: O(n), where n is the number of columns. Each pass visits every column once, with a few additions and comparisons per column.
  • Space: O(1). The method keeps three long totals and the loop index. The running totals replace arrays of prefix and suffix sums.

Splitting an array at each position into a sum before and a sum after is also the heart of Number of Ways to Split Array.