[InterviewBit] Maximum Unsorted Subarray

Maximum Unsorted Subarray

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vector<int> Solution::subUnsort(vector<int> &A) {
int n = A.size(), l = n, r = -1;
for(int i = 0; i < n; i++) {
if(i and A[i] < A[i - 1]) {
l = min(l, i - 1);
r = max(r, i);
while(l >= 0 and A[l] > A[i]) l--;
}
if(i + 1 < n and A[i] > A[i + 1]) {
l = min(l, i);
r = max(r, i + 1);
while(r < n and A[r] < A[i]) r++;
}
}

if(l == n) return {-1};
return {l + 1, r - 1};
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/14/PS/interviewbit/maximum-unsorted-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.