Given an array of positive integers, truncate it such that 2×min becomes more than max, and the total number of removals is minimal. The min and max are the minimum and the maximum elements in the array, respectively. The elements can be removed either from the start or end of the array if the above condition does not meet.

For example,

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

Practice this problem

1. Brute-Force Solution

The idea is to recursively find the optimal value by removing elements from each side of the array and choosing the end, leading to fewer removals. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The minimum number of removals is 3

Java


Download  Run Code

Output:

The minimum number of removals is 3

Python


Download  Run Code

Output:

The minimum number of removals is 3

The time complexity of the above solution is O(2n), where n is the size of the input. The auxiliary space required by the program is O(n2) for recursion (call stack).

2. Dynamic Programming Solution

On drawing a recursion tree for the above solution, we can easily see that each subproblem gets repeated several times. The problem satisfies both optimal substructure and overlapping subproblems properties of dynamic programming, so the subproblem solutions can be derived using memoization or in a bottom-up manner.

Following is the dynamic programming solution in C++, Java, and Python, that iteratively build up a table of values T[i][j] to prevent redundant calculations of the same value:

C++


Download  Run Code

Output:

The minimum number of removals is 3

Java


Download  Run Code

Output:

The minimum number of removals is 3

Python


Download  Run Code

Output:

The minimum number of removals is 3

The above solution takes O(n3) time and O(n2) extra space. Refer to the following post for another approach to solve this problem that doesn’t require any extra space, handles negative numbers, and offers better runtime than the dynamic programming algorithm.

Find minimum removals required in an array to satisfy given constraints