Skip to content

Commit 08ff287

Browse files
authored
feat: add solutions to lcci problem: No.17.05 (#923)
No.17.05.Find Longest Subarray
1 parent 507b20a commit 08ff287

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

lcci/17.05.Find Longest Subarray/README.md

+25
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,31 @@ func findLongestSubarray(array []string) []string {
149149
}
150150
```
151151

152+
### **TypeScript**
153+
154+
```ts
155+
function findLongestSubarray(array: string[]): string[] {
156+
const vis = new Map();
157+
vis.set(0, -1);
158+
let s = 0,
159+
mx = 0,
160+
k = 0;
161+
for (let i = 0; i < array.length; ++i) {
162+
s += array[i] >= 'A' ? 1 : -1;
163+
if (vis.has(s)) {
164+
const j = vis.get(s);
165+
if (mx < i - j) {
166+
mx = i - j;
167+
k = j + 1;
168+
}
169+
} else {
170+
vis.set(s, i);
171+
}
172+
}
173+
return array.slice(k, k + mx);
174+
}
175+
```
176+
152177
### **...**
153178

154179
```

lcci/17.05.Find Longest Subarray/README_EN.md

+25
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,31 @@ func findLongestSubarray(array []string) []string {
137137
}
138138
```
139139

140+
### **TypeScript**
141+
142+
```ts
143+
function findLongestSubarray(array: string[]): string[] {
144+
const vis = new Map();
145+
vis.set(0, -1);
146+
let s = 0,
147+
mx = 0,
148+
k = 0;
149+
for (let i = 0; i < array.length; ++i) {
150+
s += array[i] >= 'A' ? 1 : -1;
151+
if (vis.has(s)) {
152+
const j = vis.get(s);
153+
if (mx < i - j) {
154+
mx = i - j;
155+
k = j + 1;
156+
}
157+
} else {
158+
vis.set(s, i);
159+
}
160+
}
161+
return array.slice(k, k + mx);
162+
}
163+
```
164+
140165
### **...**
141166

142167
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function findLongestSubarray(array: string[]): string[] {
2+
const vis = new Map();
3+
vis.set(0, -1);
4+
let s = 0,
5+
mx = 0,
6+
k = 0;
7+
for (let i = 0; i < array.length; ++i) {
8+
s += array[i] >= 'A' ? 1 : -1;
9+
if (vis.has(s)) {
10+
const j = vis.get(s);
11+
if (mx < i - j) {
12+
mx = i - j;
13+
k = j + 1;
14+
}
15+
} else {
16+
vis.set(s, i);
17+
}
18+
}
19+
return array.slice(k, k + mx);
20+
}

0 commit comments

Comments
 (0)