Skip to content

Commit 5cc5678

Browse files
authored
feat: add ts solution to lc problem: No.1911 (doocs#1192)
No.1911.Maximum Alternating Subsequence Sum
1 parent 22c9caf commit 5cc5678

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,31 @@ func max(a, b int) int {
212212
}
213213
```
214214

215+
### **TypeScript**
216+
217+
```ts
218+
function maxAlternatingSum(nums: number[]): number {
219+
const n = nums.length;
220+
const f: number[] = new Array(n + 1).fill(0);
221+
const g = f.slice();
222+
for (let i = 1; i <= n; ++i) {
223+
f[i] = Math.max(g[i - 1] + nums[i - 1], f[i - 1]);
224+
g[i] = Math.max(f[i - 1] - nums[i - 1], g[i - 1]);
225+
}
226+
return Math.max(f[n], g[n]);
227+
}
228+
```
229+
230+
```ts
231+
function maxAlternatingSum(nums: number[]): number {
232+
let [f, g] = [0, 0];
233+
for (const x of nums) {
234+
[f, g] = [Math.max(g - x, f), Math.max(f + x, g)];
235+
}
236+
return g;
237+
}
238+
```
239+
215240
### **...**
216241

217242
```

solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,31 @@ func max(a, b int) int {
180180
}
181181
```
182182

183+
### **TypeScript**
184+
185+
```ts
186+
function maxAlternatingSum(nums: number[]): number {
187+
const n = nums.length;
188+
const f: number[] = new Array(n + 1).fill(0);
189+
const g = f.slice();
190+
for (let i = 1; i <= n; ++i) {
191+
f[i] = Math.max(g[i - 1] + nums[i - 1], f[i - 1]);
192+
g[i] = Math.max(f[i - 1] - nums[i - 1], g[i - 1]);
193+
}
194+
return Math.max(f[n], g[n]);
195+
}
196+
```
197+
198+
```ts
199+
function maxAlternatingSum(nums: number[]): number {
200+
let [f, g] = [0, 0];
201+
for (const x of nums) {
202+
[f, g] = [Math.max(g - x, f), Math.max(f + x, g)];
203+
}
204+
return g;
205+
}
206+
```
207+
183208
### **...**
184209

185210
```
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
function maxAlternatingSum(nums: number[]): number {
2+
let [f, g] = [0, 0];
3+
for (const x of nums) {
4+
[f, g] = [Math.max(g - x, f), Math.max(f + x, g)];
5+
}
6+
return g;
7+
}

0 commit comments

Comments
 (0)