Skip to content

Commit 8512291

Browse files
Time: 1 ms (99.95%), Space: 40.3 MB (65.87%) - LeetHub
1 parent a1176f3 commit 8512291

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public int findUnsortedSubarray(int[] nums) {
3+
4+
int low=0,high=nums.length-1;
5+
6+
//find the first unsorted element from beginning
7+
while(low<nums.length-1&&nums[low]<=nums[low+1])
8+
low++;
9+
10+
if(low==nums.length-1)
11+
return 0;
12+
13+
14+
//find the first unsorted element from end of the array
15+
while(high>0&&nums[high]>=nums[high-1])
16+
high--;
17+
18+
int minEl=Integer.MAX_VALUE;
19+
int maxEl=Integer.MIN_VALUE;
20+
for(int i=low;i<=high;i++)
21+
{
22+
minEl=Math.min(minEl,nums[i]);
23+
maxEl=Math.max(maxEl,nums[i]);
24+
}
25+
26+
//extend subarray if we encounter a element less than minimum to include
27+
while(low>0&&nums[low-1]>minEl)
28+
low--;
29+
30+
31+
//extend subarray if we encounter a element greater than max of the subarray to include it
32+
33+
while(high<nums.length-1&&nums[high+1]<maxEl)
34+
high++;
35+
36+
37+
return high-low+1;
38+
39+
40+
}
41+
}

0 commit comments

Comments
 (0)