Given an integer array, 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,

Input:  [4, 6, 1, 7, 5, 9, 2]
 
Output: The minimum number of removals is 4
 
The trimmed array is [7, 5, 9] where 9 < 2 × 5.
 
 
Input:  [4, 2, 6, 4, 9]
 
Output: The minimum number of removals is 3
 
The trimmed array is [6, 4] where 6 < 2 × 4.

Practice this problem

The idea is simple and effective – instead of removing elements from the array, view the problem as finding the largest subarray whose maximum element is less than twice the minimum.

Traverse the array from left to right and consider each element a starting point of a subarray. Then, with the starting index of the subarray fixed, greedily choose its other end as much away from it as possible. We can do this by expanding the subarray towards the right, one element at a time, provided that the newly added element satisfies the given condition. Do this for all subarrays to find the maximum size subarray. The minimum number of removals needed will be the difference between the array’s size and the maximum size subarray length.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum number of removals is 4

Java


Download  Run Code

Output:

The minimum number of removals is 4

Python


Download  Run Code

Output:

The minimum number of removals is 4

The time complexity of the above solution is O(n2) and doesn’t require any extra space, where n is the size of the input.

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