[LeetCode] Shortest Subarray to be Removed to Make Array Sorted

1574. Shortest Subarray to be Removed to Make Array Sorted

Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.

A subarray is a contiguous subsequence of the array.

Return the length of the shortest subarray to remove.

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
class Solution {
public:
int findLengthOfShortestSubarray(vector<int>& arr) {
int res = arr.size() - 1, last;
map<int, int> increase;
for(last = 0; last < arr.size() - 1; last++) {
increase[arr[last]] = last;
if(arr[last] > arr[last + 1])
break;
res--;
}

for(int i = arr.size() - 1; i > last; --i) {
auto it = increase.lower_bound(arr[i]);
if(it->first == arr[i]) {
res = min(res, i - it->second - 1);
} else if(it == begin(increase)) {
res = min(res, i);
} else {
res = min(res, i - prev(it)->second - 1);
}

if(arr[i] < arr[i - 1])
break;
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/26/PS/LeetCode/shortest-subarray-to-be-removed-to-make-array-sorted/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.