1
var findLengthOfShortestSubarray = function (arr) {
2
const n = arr.length;
3

4
if (n <= 1) {
5
return 0;
6
}
7

8
let prefix = 1;
9

10
while (prefix < n) {
11
if (arr[prefix - 1] <= arr[prefix]) {
12
prefix++;
13
} else {
14
break;
15
}
16
}
17

18
if (prefix === n) {
19
return 0;
20
}
21

22
let suffix = 1;
23

24
while (suffix < n) {
25
const i = n - 1 - suffix;
26

27
if (arr[i] <= arr[i + 1]) {
28
suffix++;
29
} else {
30
break;
31
}
32
}
33

34
let res = Math.min(n - prefix, n - suffix);
35
let left = 0;
36
let right = n - suffix;
37

38
while (left < prefix && right < n) {
39
if (arr[left] <= arr[right]) {
40
res = Math.min(res, right - left - 1);
41
left++;
42
} else {
43
right++;
44
}
45
}
46

47
return res;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0