| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.GridGame; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class GridGamePrefixSum : IGridGame |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public long GridGame(int[][] grid) |
| 3 | 24 | | { |
| 3 | 25 | | var n = grid[0].Length; |
| | 26 | |
|
| 3 | 27 | | var topPrefixSum = new long[n]; |
| 3 | 28 | | var bottomPrefixSum = new long[n]; |
| | 29 | |
|
| 3 | 30 | | topPrefixSum[0] = grid[0][0]; |
| 3 | 31 | | bottomPrefixSum[0] = grid[1][0]; |
| | 32 | |
|
| 20 | 33 | | for (var i = 1; i < n; i++) |
| 7 | 34 | | { |
| 7 | 35 | | topPrefixSum[i] = topPrefixSum[i - 1] + grid[0][i]; |
| 7 | 36 | | bottomPrefixSum[i] = bottomPrefixSum[i - 1] + grid[1][i]; |
| 7 | 37 | | } |
| | 38 | |
|
| 3 | 39 | | var result = long.MaxValue; |
| | 40 | |
|
| 26 | 41 | | for (var i = 0; i < n; i++) |
| 10 | 42 | | { |
| 10 | 43 | | var topRemaining = topPrefixSum[n - 1] - topPrefixSum[i]; |
| | 44 | |
|
| 10 | 45 | | long bottomCollected = 0; |
| | 46 | |
|
| 10 | 47 | | if (i > 0) |
| 7 | 48 | | { |
| 7 | 49 | | bottomCollected = bottomPrefixSum[i - 1]; |
| 7 | 50 | | } |
| | 51 | |
|
| 10 | 52 | | var secondRobotPoints = Math.Max(topRemaining, bottomCollected); |
| | 53 | |
|
| 10 | 54 | | result = Math.Min(result, secondRobotPoints); |
| 10 | 55 | | } |
| | 56 | |
|
| 3 | 57 | | return result; |
| 3 | 58 | | } |
| | 59 | | } |