The code is slow on larger arrays because of the nested for
loops. The number of times the inner loop runs depends on the length of the array. The outer loop runs arr_len
times and the inner loop runs arr_len/2
times on average. As a result the code in the loop runs arr_len**2 / 2
. If the size of the array doubles, the amount of work the code does quadruples. If the size goes up by a thousand, the work goes up by a million. You may see this described as O(n^2) time complexity.
The trick is to find an algorithm than scans the array once (or maybe a few times). Here are some observations that might help:
If the 1st element of a subarray is x
, then a valid subarray is a sequence of x
's, a sequence of x
's and x+1
's or a sequence of x
's and x-1
's. For example, [2,2,2], [2,2,3,3,2,3], and [2,1,1,2,2,2,2,2] could be valid subarrays.
Depending on the form of the subarray, min, max
is either (x,x)
, (x, x+1)
, or (x-1, x)
. And all the values in the valid subarray are min
or max
.
Depending on the value that ends the current subarray, a new subarray can start where it changed between min
to max
, or the reverse. Or it could start with the new value. For example, [1,1,2,2,3,3] has overlapping subarrays [1,1,2,2] and [2,2,3,3]. But [1,1,2,2,0,0] doesn't: [1,1,2,2] and [0,0].