Input: arr =[1,2,3,10,4,2,3,5]Output: 3Explanation: The shortest subarray we can remove is[10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.Another correct solution is to remove the subarray [3,10,4].
Example 2:
1
2
3
Input: arr =[5,4,3,2,1]Output: 4Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
1
2
3
Input: arr =[1,2,3]Output: 0Explanation: The array is already non-decreasing. We do not need to remove any elements.
Identify the longest non-decreasing subarray from the beginning.
Identify the longest non-decreasing subarray from the end.
Use a two-pointer technique to find the shortest subarray that can be removed such that the remaining array is non-decreasing by combining parts of the two subarrays from steps 1 and 2.
The length of the shortest subarray to remove will be the minimum of all possible combinations.
publicclassSolution {
publicintfindLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
int left = 0;
// Find the longest non-decreasing subarray from the startwhile (left < n - 1 && arr[left]<= arr[left + 1]) {
left++;
}
// If the entire array is non-decreasingif (left == n - 1) {
return 0;
}
int right = n - 1;
// Find the longest non-decreasing subarray from the endwhile (right > 0 && arr[right - 1]<= arr[right]) {
right--;
}
// Compute the minimum length to removeint ans = Math.min(n - left - 1, right);
int i = 0, j = right;
while (i <= left && j < n) {
if (arr[i]<= arr[j]) {
ans = Math.min(ans, j - i - 1);
i++;
} else {
j++;
}
}
return ans;
}
}
classSolution:
deffindLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
left =0# Find the longest non-decreasing subarray from the startwhile left < n -1and arr[left] <= arr[left +1]:
left +=1# If the entire array is non-decreasingif left == n -1:
return0 right = n -1# Find the longest non-decreasing subarray from the endwhile right >0and arr[right -1] <= arr[right]:
right -=1# Compute the minimal length to remove ans = min(n - left -1, right)
i, j =0, right
while i <= left and j < n:
if arr[i] <= arr[j]:
ans = min(ans, j - i -1)
i +=1else:
j +=1return ans
⏰ Time complexity: O(n), as the solution involves two passes through the array to find the longest non-decreasing subarrays from the start and end, and another pass to combine them.