![]() |
VOOZH | about |
Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array.
Number of removals should be minimum.
Examples:
arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200}
Output: 4
We need to remove 4 elements (4, 5, 100, 200)
so that 2*min becomes more than max.
arr[] = {4, 7, 5, 6}
Output: 0
We don't need to remove any element as
4*2 > 7 (Note that min = 4, max = 8)
arr[] = {20, 7, 5, 6}
Output: 1
We need to remove 20 so that 2*min becomes
more than max
arr[] = {20, 4, 1, 3}
Output: 3
We need to remove any three elements from ends
like 20, 4, 1 or 4, 1, 3 or 20, 3, 1 or 20, 4, 1Naive Solution:
A naive solution is to try every possible case using recurrence. Following is the naive recursive algorithm. Note that the algorithm only returns minimum numbers of removals to be made, it doesn't print the trimmed array. It can be easily modified to print the trimmed array as well.
// Returns minimum number of removals to be made in // arr[l..h] minRemovals(int arr[], int l, int h) 1) Find min and max in arr[l..h] 2) If 2*min > max, then return 0. 3) Else return minimum of "minRemovals(arr, l+1, h) + 1" and "minRemovals(arr, l, h-1) + 1"
Following is the implementation of above algorithm.
4
Time complexity: Time complexity of the above function can be written as following
T(n) = 2T(n-1) + O(n)
An upper bound on solution of above recurrence would be O(n x 2n).
Auxiliary Space: O(1)
Dynamic Programming:
The above recursive code exhibits many overlapping subproblems. For example minRemovals(arr, l+1, h-1) is evaluated twice. So Dynamic Programming is the choice to optimize the solution. Following is Dynamic Programming based solution.
3
Time Complexity: O(n3) where n is the number of elements in arr[].
Auxiliary Space: O(n^2)
Further Optimizations:
The above code can be optimized in many ways.
A O(n^2) Solution:
The idea is to find the maximum sized subarray such that 2*min > max. We run two nested loops, the outer loop chooses a starting point and the inner loop chooses ending point for the current starting point. We keep track of longest subarray with the given property.
Following is the implementation of the above approach. Thanks to Richard Zhang for suggesting this solution.
4
Time Complexity: O(N2)
Auxiliary Space: O(1)