# Longest subarray: minimum first element, maximum last element

I have to write a program that, given an array of n numbers, finds the longest contiguous subarray whose minimum is the first element of the subarray and maximum the last element of the subarray. For example, with [5, 18, 2, 12, 4, 7, 13, -2, -5, 12] the answer should be [2, 12, 4, 7, 13] (2 <= of all the elements of the subarray, 13 >= of all the elements of the subarray). If possible, the time complexity in the worst case has to be equal to O(n). If it isn't possible, could you explain me why? I already tried to find the minimums and then the maximums, but doesn't work with arrays like [-1,12,1,2,3,4] (min=-1, max=12 but the longest is [1,2,3,4]). I also tried to split the array when there is an element followed by a smaller element and then merge the subarrays, but it doesn't work for arrays like [2,15,6,10,3,20] (I can't merge [2,15] and [6,10]).

asked Feb 5, 2017

```List<Integer> getMaxList(List<Integer> list) {
int s = list.size();
int max[] = new int[s];
int min[] = new int[s];
min[0] = 0;
max[s-1] = s-1;
for(int i=1;i<s;i++) {
if(list.get(min[i-1])>list.get(i)){
min[i] = i;
}else{
min[i] = min[i-1];
}
}
for(int j=s-2;j>=0;j--) {
if(list.get(max[j+1])<list.get(j)){
max[j] = j;
}else{
max[j] = max[j+1];
}
}

int m =1;
int initIndex = 0;
for(int i=0;i<s;i++) {
if(min[max[i]] <= i){
if(m < max[i]-i +1) {
m = max[i] - i + 1;
initIndex = i;
}
}
}

return list.subList(initIndex,initIndex + m);
}```
answered Feb 15, 2017

Thanks but it doesn't work with  {1,15,5,5,5,5,5,5,5,5,-1,8,10}

Thanks but it doesn't work with  {1,15,5,5,5,5,5,5,5,5,-1,8,10}

answered Feb 15, 2017
reshown Mar 30, 2017