Given an array of integers, trim it such that its maximum element becomes less than twice the minimum, return the minimum number of removals required for the conversion.

For example,

The idea is straightforward and effective – instead of removing elements from the array, view the problem as finding the largest sub-array whose maximum element is less than twice the minimum.
The idea is to traverse the array from left to right and consider each element a starting point of a sub-array. Then, with the starting index of sub-array fixed, greedily choose its other end as much away from it as possible. This can be done by expanding the sub-array towards the right, one element at a time, provided that the newly added element satisfies the given condition. Do this for all sub-arrays to find the maximum size sub-array. The minimum number of removals needed will be the difference between the array’s size and the length of the maximum size sub-array.
The algorithm can be implemented as follows in C++, Java, and Python:

C++

Download   Run Code

Output:

The minimum number of removals are 4

Java

Download   Run Code

Output:

The minimum number of removals are 4

Python

Download   Run Code

Output:

The minimum number of removals are 4

Download   Run Code
Output:

The minimum number of removals are 4

Download   Run Code
Output:

The minimum number of removals are 4

Download   Run Code
Output:

The minimum number of removals are 4

The time complexity of the above solution is O(n2) and requires O(1) extra space.

Exercise: Modify the solution to print the trimmed array as well.

source