Very simple Linear solution with full explanation and diagram (Prefix sum)

Let Robot 1 be alice and robot 2 be bob. for more cleareance

image

The path clearly separates the field into two independent pieces — suffix of the first row and the prefix of the second row. Bob can't grab the coins from both of them at once. However, he can grab either of them fully. So the optimal path for him will be one of these two options.

You can precalculate some prefix sums and become able to get the Bob's score given the Alice's path. Alice has m possibly paths, so you can iterate over them and choose the minimum answer.

However, prefix sums are not required, since you can quickly recalculate both needed sums while iterating over the Alice's column to go down in.

Overall complexity: O(m) per testcase.

Java Solution

 public long gridGame(int[][] arr) {
            
     int m = arr[0].length;
        
         long[] pre1 = new long[m + 1];
        long[] pre2 = new long[m + 1];
        for (int i = 1; i <= m; i++) {
            pre1[i] = pre1[i - 1] + arr[0][i - 1];
        }
        for (int i = 1; i <= m; i++) {
            pre2[i] = pre2[i - 1] + arr[1][i - 1];
        }
        long res = Long.MAX_VALUE;
        for (int i = 0; i < m; i++) {
            res = Math.min(res, Math.max(pre1[m] - pre1[i + 1], pre2[i]));
        }
 
      return res;  
 
        
    }
Comments (0)