-
Notifications
You must be signed in to change notification settings - Fork 12
/
solution.java
37 lines (31 loc) · 1.02 KB
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public int findLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
// Step 1: Find the longest non-decreasing prefix
int left = 0;
while (left + 1 < n && arr[left] <= arr[left + 1]) {
left++;
}
// If the entire array is already sorted
if (left == n - 1)
return 0;
// Step 2: Find the longest non-decreasing suffix
int right = n - 1;
while (right > 0 && arr[right - 1] <= arr[right]) {
right--;
}
// Step 3: Find the minimum length to remove by comparing prefix and suffix
int result = Math.min(n - left - 1, right);
// Step 4: Use two pointers to find the smallest middle part to remove
int i = 0, j = right;
while (i <= left && j < n) {
if (arr[i] <= arr[j]) {
result = Math.min(result, j - i - 1);
i++;
} else {
j++;
}
}
return result;
}
}