Skip to content

Commit ea18623

Browse files
committed
✅ [1493] sliding window
1 parent 15aa0ea commit ea18623

File tree

3 files changed

+86
-1
lines changed

3 files changed

+86
-1
lines changed

1493/my_solution.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestSubarray = function (nums) {
6+
const DELETE_COUNT = 1
7+
let l = 0, r = 0, max = 0, tmpMax = 0, k = 1
8+
9+
//[1,1,0,1]
10+
while (r < nums.length) {
11+
tmpMax++;
12+
console.log(`l: ${l}, r: ${r}, max: ${max}, tmpMax: ${tmpMax}, k: ${k}`)
13+
14+
if (nums[r] === 0) {
15+
k--;
16+
17+
if (k < 0) {
18+
console.log(`~> k: ${k}`)
19+
// l++;
20+
while (l < r) {
21+
if (nums[l] === 0) {
22+
l++;
23+
break;
24+
}
25+
26+
l++;
27+
}
28+
k++;
29+
tmpMax = r - l + 1
30+
console.log(`~> new l: ${l}, new tmpMax: ${tmpMax}`)
31+
}
32+
}
33+
34+
max = Math.max(max, tmpMax)
35+
r++;
36+
}
37+
console.log(`~> k: ${k}`)
38+
39+
return max - DELETE_COUNT;
40+
};
41+
42+
let x =
43+
longestSubarray([0, 1, 1, 1, 0, 1, 1, 0, 1])
44+
// longestSubarray([1, 1, 0, 1])
45+
// longestSubarray([1, 1, 1])
46+
47+
console.log("Res")
48+
console.log(x)

1493/solution.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestSubarray = function (nums) {
6+
const DELETE_COUNT = 1
7+
let l = 0, r = 0, max = 0, tmpMax = 0, k = 1
8+
9+
while (r < nums.length) {
10+
tmpMax++;
11+
12+
if (nums[r] === 0) {
13+
k--;
14+
15+
if (k < 0) {
16+
17+
while (l < r) {
18+
if (nums[l] === 0) {
19+
l++;
20+
break;
21+
}
22+
23+
l++;
24+
}
25+
26+
k++;
27+
tmpMax = r - l + 1
28+
}
29+
}
30+
31+
max = Math.max(max, tmpMax)
32+
r++;
33+
}
34+
35+
return max - DELETE_COUNT;
36+
};

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
- [1431. Kids With the Greatest Number of Candies](./1431/)
107107
- [1456. Maximum Number of Vowels in a Substring of Given Length](./1456/)
108108
- [1480. Running Sum of 1d Array](./1480/)
109+
- [1493. Longest Subarray of 1's After Deleting One Element](./1493/)
109110
- [1512. Number of Good Pairs](./1512/)
110111
- [1569. Number of Ways to Reorder Array to Get Same BST](./1569/)
111112
- [1572. Matrix Diagonal Sum](./1572/)
@@ -165,7 +166,7 @@ Batch create:
165166
NOTE: JS IS HERE
166167
-->
167168
```ssh
168-
chapter=1004 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
169+
chapter=1493 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
169170
```
170171
> then you can use `x` for quick debug.
171172

0 commit comments

Comments
 (0)