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]).

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