Skip to content

Commit d8bad90

Browse files
committed
feat: add ts solution to lc problem: No.2017
No.2017.Grid Game
1 parent 786860c commit d8bad90

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

Diff for: solution/2000-2099/2017.Grid Game/README.md

+28
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,18 @@
6363

6464
<!-- 这里可写通用的实现逻辑 -->
6565

66+
**方法一:前缀和**
67+
68+
我们注意到,如果确定了第一个机器人拐头向下的位置 $j$,那么第二个机器人的最优路径也就确定了,第二个机器人的最优路径就是第一行从 $j+1$ 到 $n-1$ 的前缀和,或者第二行从 $0$ 到 $j-1$ 的前缀和,取两者的最大值。
69+
70+
我们先计算第一行的后缀点数和,记为 $s_1$,第二行的前缀点数和记为 $s_2$,初始时 $s_1 = \sum_{j=0}^{n-1} grid[0][j]$, $s_2 = 0$。
71+
72+
然后我们枚举第一个机器人拐头向下的位置 $j$,此时更新 $s_1 = s_1 - grid[0][j]$, 那么第二个机器人的最优路径和就是 $max(s_1, s_2)$,我们取所有 $j$ 对应的 $max(s_1, s_2)$ 的最小值即可。然后更新 $s_2 = s_2 + grid[1][j]$。
73+
74+
枚举结束后,返回答案即可。
75+
76+
时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是网格的列数。
77+
6678
<!-- tabs:start -->
6779

6880
### **Python3**
@@ -158,6 +170,22 @@ func min(a, b int) int {
158170
}
159171
```
160172

173+
### **TypeScript**
174+
175+
```ts
176+
function gridGame(grid: number[][]): number {
177+
let ans = Number.MAX_SAFE_INTEGER;
178+
let s1 = grid[0].reduce((a, b) => a + b, 0);
179+
let s2 = 0;
180+
for (let j = 0; j < grid[0].length; ++j) {
181+
s1 -= grid[0][j];
182+
ans = Math.min(ans, Math.max(s1, s2));
183+
s2 += grid[1][j];
184+
}
185+
return ans;
186+
}
187+
```
188+
161189
### **...**
162190

163191
```

Diff for: solution/2000-2099/2017.Grid Game/README_EN.md

+16
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,22 @@ func min(a, b int) int {
146146
}
147147
```
148148

149+
### **TypeScript**
150+
151+
```ts
152+
function gridGame(grid: number[][]): number {
153+
let ans = Number.MAX_SAFE_INTEGER;
154+
let s1 = grid[0].reduce((a, b) => a + b, 0);
155+
let s2 = 0;
156+
for (let j = 0; j < grid[0].length; ++j) {
157+
s1 -= grid[0][j];
158+
ans = Math.min(ans, Math.max(s1, s2));
159+
s2 += grid[1][j];
160+
}
161+
return ans;
162+
}
163+
```
164+
149165
### **...**
150166

151167
```

Diff for: solution/2000-2099/2017.Grid Game/Solution.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function gridGame(grid: number[][]): number {
2+
let ans = Number.MAX_SAFE_INTEGER;
3+
let s1 = grid[0].reduce((a, b) => a + b, 0);
4+
let s2 = 0;
5+
for (let j = 0; j < grid[0].length; ++j) {
6+
s1 -= grid[0][j];
7+
ans = Math.min(ans, Math.max(s1, s2));
8+
s2 += grid[1][j];
9+
}
10+
return ans;
11+
}

0 commit comments

Comments
 (0)