-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsolution.go
43 lines (36 loc) · 944 Bytes
/
solution.go
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
38
39
40
41
42
43
func findLengthOfShortestSubarray(arr []int) int {
n := len(arr)
// Step 1: Find the longest non-decreasing prefix
left := 0
for 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
right := n - 1
for right > 0 && arr[right-1] <= arr[right] {
right--
}
// Step 3: Find the minimum length to remove by comparing prefix and suffix
result := min(n-left-1, right)
// Step 4: Use two pointers to find the smallest middle part to remove
i, j := 0, right
for i <= left && j < n {
if arr[i] <= arr[j] {
result = min(result, j-i-1)
i++
} else {
j++
}
}
return result
}
func min(a, b int) int {
if a < b {
return a
}
return b
}