Skip to content

Commit bc735c9

Browse files
authored
Create 1493-longest-subarray-of-1s-after-deleting-one-element.js
1 parent 48ec339 commit bc735c9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const longestSubarray = function(nums) {
6+
const n = nums.length
7+
let res = 0
8+
const pre = Array(n).fill(0)
9+
const suf = Array(n).fill(0)
10+
11+
let cnt = 0, hasZero = false
12+
for(let i = 0; i < n; i++) {
13+
if(nums[i] === 1) {
14+
cnt++
15+
pre[i] = cnt
16+
res = Math.max(res, cnt)
17+
} else {
18+
hasZero = true
19+
cnt = 0
20+
pre[i] = cnt
21+
}
22+
}
23+
if(!hasZero) res--
24+
25+
cnt = 0
26+
27+
for(let i = n - 1; i >= 0; i--) {
28+
if(nums[i] === 1) {
29+
cnt++
30+
suf[i] = cnt
31+
32+
} else {
33+
cnt = 0
34+
suf[i] = cnt
35+
36+
}
37+
}
38+
// console.log(pre,suf)
39+
for(let i = 1; i < n - 1; i++) {
40+
if(nums[i] === 0) {
41+
res = Math.max(res, pre[i - 1] + suf[i + 1])
42+
}
43+
}
44+
45+
46+
return res
47+
};

0 commit comments

Comments
 (0)