Skip to content

2017. Grid Game 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  long long gridGame(vector<vector<int>>& grid) {
    const int n = grid[0].size();
    long ans = LONG_MAX;
    long sumRow0 = accumulate(grid[0].begin(), grid[0].end(), 0L);
    long sumRow1 = 0;

    for (int i = 0; i < n; ++i) {
      sumRow0 -= grid[0][i];
      ans = min(ans, max(sumRow0, sumRow1));
      sumRow1 += grid[1][i];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public long gridGame(int[][] grid) {
    final int n = grid[0].length;
    long ans = Long.MAX_VALUE;
    long sumRow0 = Arrays.stream(grid[0]).asLongStream().sum();
    long sumRow1 = 0;

    for (int i = 0; i < n; ++i) {
      sumRow0 -= grid[0][i];
      ans = Math.min(ans, Math.max(sumRow0, sumRow1));
      sumRow1 += grid[1][i];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def gridGame(self, grid: list[list[int]]) -> int:
    n = len(grid[0])
    ans = math.inf
    sumRow0 = sum(grid[0])
    sumRow1 = 0

    for i in range(n):
      sumRow0 -= grid[0][i]
      ans = min(ans, max(sumRow0, sumRow1))
      sumRow1 += grid[1][i]

    return ans