I have been wrestling with this problem for quite a bit:
Given an integer array
nums
, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
(cmp. https://leetcode.com/problems/shortest-unsorted-continuous-subarray/).
I'm still stuck on the main approach of this problem. It's splitting my head in two.
Suppose we have this given array:
[1,2,5,3,7,10,9,12]
The answer is "5", pertaining the subarray between '5' and '9'.
My approach for this problem is basically like this:
Create a "maxes" array where every index represents the max value found up to that index.
Create a "mins" array where every index represents the min value found up to that index.
The respective discrepancies between 'maxes' and the input array, and the discrepancies between 'mins' and the input array, will give us the 'start' and 'end' index. Subtract the two to find the length of the subarray. (This step isn't important for my question, I'm stuck before this part.)
**
Thus for the "maxes" array, it would look like:
input: [1,2,5,3,7,10,9,12]
->
maxes: [1,2,5,5,7,10,10,12]
Where index 0 is "1" because '1' is the "max" value found up to that index. Index 1 is "2" because '2' is the "max' value found up to that index. And so forth.
We then find the highest index that's a mismatch between the input array and maxes array.
My question is when I try this approach for the 'mins' array:
input: [1,2,5,3,7,10,9,12]
->
mins: [1,1,1,1,1,1,1,1]
If I start from the left, it all just becomes 1.
Should I start at the end (right) instead? And if I do, why do I have to start it at the end?