|
| 1 | +# 1574. Shortest Subarray to be Removed to Make Array Sorted |
| 2 | +Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. |
| 3 | + |
| 4 | +Return *the length of the shortest subarray to remove*. |
| 5 | + |
| 6 | +A **subarray** is a contiguous subsequence of the array. |
| 7 | + |
| 8 | +#### Example 1: |
| 9 | +<pre> |
| 10 | +<strong>Input:</strong> arr = [1,2,3,10,4,2,3,5] |
| 11 | +<strong>Output:</strong> 3 |
| 12 | +<strong>Explanation:</strong> 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. |
| 13 | +Another correct solution is to remove the subarray [3,10,4]. |
| 14 | +</pre> |
| 15 | + |
| 16 | +#### Example 2: |
| 17 | +<pre> |
| 18 | +<strong>Input:</strong> arr = [5,4,3,2,1] |
| 19 | +<strong>Output:</strong> 4 |
| 20 | +<strong>Explanation:</strong> 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]. |
| 21 | +</pre> |
| 22 | + |
| 23 | +#### Example 3: |
| 24 | +<pre> |
| 25 | +<strong>Input:</strong> arr = [1,2,3] |
| 26 | +<strong>Output:</strong> 0 |
| 27 | +<strong>Explanation:</strong> The array is already non-decreasing. We do not need to remove any elements. |
| 28 | +</pre> |
| 29 | + |
| 30 | +#### Constraints: |
| 31 | +* <code>1 <= arr.length <= 10<sup>5</sup></code> |
| 32 | +* <code>0 <= arr[i] <= 10<sup>9</sup></code> |
| 33 | + |
| 34 | +## Solutions (Rust) |
| 35 | + |
| 36 | +### 1. Solution |
| 37 | +```Rust |
| 38 | +impl Solution { |
| 39 | + pub fn find_length_of_shortest_subarray(arr: Vec<i32>) -> i32 { |
| 40 | + let mut arr = arr; |
| 41 | + let mut i = arr.len(); |
| 42 | + let mut ret = arr.len() - 1; |
| 43 | + |
| 44 | + arr.insert(0, 0); |
| 45 | + |
| 46 | + while i > 0 && arr[i - 1] <= arr[i] { |
| 47 | + i -= 1; |
| 48 | + } |
| 49 | + |
| 50 | + if i == 0 { |
| 51 | + return 0; |
| 52 | + } |
| 53 | + |
| 54 | + for j in 0..arr.len() { |
| 55 | + if j > 0 && arr[j - 1] > arr[j] { |
| 56 | + break; |
| 57 | + } |
| 58 | + |
| 59 | + while i < arr.len() && arr[i] < arr[j] { |
| 60 | + i += 1; |
| 61 | + } |
| 62 | + |
| 63 | + ret = ret.min(i - j - 1); |
| 64 | + } |
| 65 | + |
| 66 | + ret as i32 |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments