Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Remove minimum elements from either side such that 2*min becomes more than max
Next article icon

Remove minimum elements from array so that max <= 2 * min

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr, the task is to remove minimum number of elements such that after their removal, max(arr) <= 2 * min(arr). 

Examples:

Input: arr[] = {4, 5, 3, 8, 3} 
Output: 1 Remove 8 from the array. 

Input: arr[] = {1, 2, 3, 4} 
Output: 1 Remove 1 from the array.

Approach: Let us fix each value as the minimum value say x and find number of terms that are in range [x, 2*x]. This can be done using prefix-sums, we can use map (implements self balancing BST) instead of array as the values can be large. The remaining terms which are not in range [x, 2*x] will have to be removed. So, across all values of x, we choose the one which maximises the number of terms in range [x, 2*x].

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum removals from
// arr such that max(arr) <= 2 * min(arr)
int minimumRemovals(int n, int a[])
{
    // Count occurrence of each element
    map<int, int> ct;
    for (int i = 0; i < n; i++)
        ct[a[i]]++;
 
    // Take prefix sum
    int sm = 0;
    for (auto mn : ct) {
        sm += mn.second;
        ct[mn.first] = sm;
    }
 
    int mx = 0, prev = 0;
    for (auto mn : ct) {
 
        // Chosen minimum
        int x = mn.first;
        int y = 2 * x;
        auto itr = ct.upper_bound(y);
        itr--;
 
        // Number of elements that are in
        // range [x, 2x]
        int cr = (itr->second) - prev;
        mx = max(mx, cr);
        prev = mn.second;
    }
 
    // Minimum elements to be removed
    return n - mx;
}
 
// Driver Program to test above function
int main()
{
    int arr[] = { 4, 5, 3, 8, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minimumRemovals(n, arr);
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
public class Main {
    // Function to return the minimum removals from
    // arr such that max(arr) <= 2 * min(arr)
    public static int minimumRemovals(int n, int[] a) {
        // Count occurrence of each element
        Map<Integer, Integer> ct = new HashMap<>();
        for (int i = 0; i < n; i++) {
            ct.put(a[i], ct.getOrDefault(a[i], 0) + 1);
        }
     
        // Take prefix sum
        int sm = 0;
        for (int mn : ct.keySet()) {
            sm += ct.get(mn);
            ct.put(mn, sm);
        }
     
        int mx = 0, prev = 0;
        for (int mn : ct.keySet()) {
            // Chosen minimum
            int x = mn;
            int y = 2 * x;
            List<Integer> keysList = new ArrayList<>(ct.keySet());
            int index = Collections.binarySearch(keysList, y);
            int pos = index >= 0 ? index : -(index + 1) - 1;
            Integer itr = pos >= 0 ? ct.get(keysList.get(pos)) : null;
     
            // Number of elements that are in
            // range [x, 2x]
            int cr = (itr != null ? itr : 0) - prev;
            mx = Math.max(mx, cr);
            prev = ct.get(mn);
        }
     
        // Minimum elements to be removed
        return n - mx;
    }
 
    // Driver Program to test above function
    public static void main(String[] args) {
        int[] arr = { 4, 5, 3, 8, 3 };
        int n = arr.length;
        System.out.println(minimumRemovals(n, arr));
    }
}
 
// This code is contributed by codebraxnzt
 
 

Python3




# Python3 implementation of the approach
from bisect import bisect_left as upper_bound
 
# Function to return the minimum removals from
# arr such that max(arr) <= 2 * min(arr)
def minimumRemovals(n, a):
     
    # Count occurrence of each element
    ct = dict()
    for i in a:
        ct[i] = ct.get(i, 0) + 1
 
    # Take prefix sum
    sm = 0
    for mn in ct:
        sm += ct[mn]
        ct[mn] = sm
 
    mx = 0
    prev = 0;
    for mn in ct:
 
        # Chosen minimum
        x = mn
        y = 2 * x
        itr = upper_bound(list(ct), y)
 
        # Number of elements that are in
        # range [x, 2x]
        cr = ct[itr] - prev
        mx = max(mx, cr)
        prev = ct[mn]
 
    # Minimum elements to be removed
    return n - mx
 
# Driver Code
arr = [4, 5, 3, 8, 3]
n = len(arr)
print(minimumRemovals(n, arr))
 
# This code is contributed by Mohit Kumar
 
 

C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
public class MainClass
{
    // Function to return the minimum removals from
    // arr such that max(arr) <= 2 * min(arr)
    public static int minimumRemovals(int n, int[] a)
    {
        // Count occurrence of each element
        Dictionary<int, int> ct = new Dictionary<int, int>();
        for (int i = 0; i < n; i++)
        {
            if (ct.ContainsKey(a[i]))
            {
                ct[a[i]]++;
            }
            else
            {
                ct[a[i]] = 1;
            }
        }
 
        // Take prefix sum
        int sm = 0;
        List<int> keysList = new List<int>(ct.Keys);
        keysList.Sort();
        foreach (int mn in keysList)
        {
            sm += ct[mn];
            ct[mn] = sm;
        }
 
        int mx = 0, prev = 0;
        foreach (int mn in keysList)
        {
            // Chosen minimum
            int x = mn;
            int y = 2 * x;
 
            int index = keysList.BinarySearch(y);
            int pos = index >= 0 ? index : -(index + 1) - 1;
            int itr = pos >= 0 ? ct[keysList[pos]] : 0;
 
            // Number of elements that are in
            // range [x, 2x]
            int cr = itr - prev;
            mx = Math.Max(mx, cr);
            prev = ct[mn];
        }
 
        // Minimum elements to be removed
        return n - mx;
    }
 
    // Driver Program to test above function
    public static void Main()
    {
        int[] arr = { 4, 5, 3, 8, 3 };
        int n = arr.Length;
        Console.WriteLine(minimumRemovals(n, arr));
    }
}
 
// This code is contributed by Prince Kumar
 
 

Javascript




// JavaScript implementation of the approach
// Function to return the minimum removals from arr such that max(arr) <= 2 * min(arr)
 
function minimumRemovals(n, a){
    // Import upper_bound from bisect
    const upper_bound = (arr, x) => {
        let low = 0, high = arr.length;
        while (low < high) {
            const mid = (low + high) >>> 1;
            if (x >= arr[mid]) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }
   
    // Count occurrence of each element
    let ct = new Map();
    for (let i of a){
        ct.set(i, (ct.get(i) || 0) + 1);
    }
 
    // Take prefix sum
    let sm = 0;
    for (let mn of ct.keys()){
        sm += ct.get(mn);
        ct.set(mn, sm);
    }
 
    let mx = 0;
    let prev = 0;
    for (let mn of ct.keys()){
        // Chosen minimum
        let x = mn;
        let y = 2 * x;
        let itr = upper_bound(Array.from(ct.keys()), y);
 
        // Number of elements that are in range [x, 2x]
        let cr = ct.get([...ct.keys()][itr-1]) - ct.get(mn) + prev;
        mx = Math.max(mx, cr);
        prev = ct.get(mn) - (ct.get(mn - 1) || 0);
    }
 
    // Minimum elements to be removed
    return n - mx;
}
 
// Driver Code
let arr = [4, 5, 3, 8, 3];
let n = arr.length;
console.log(minimumRemovals(n, arr));
 
// This code is contributed by princekumaras
 
 
Output
1


Next Article
Remove minimum elements from either side such that 2*min becomes more than max

A

Abdullah Aslam
Improve
Article Tags :
  • Arrays
  • Binary Search Tree
  • DSA
  • cpp-map
Practice Tags :
  • Arrays
  • Binary Search Tree

Similar Reads

  • Remove minimum elements from the array such that 2*min becomes more than max
    Given an unsorted array, arr[]. The task is to find the minimum number of removals required such that twice the minimum element in the array is greater than or equal to the maximum in the array. Examples: Input: arr[] = [4, 5, 100, 9, 10, 11, 12, 15, 200]Output: 4Explanation: In the given array 4 el
    7 min read
  • Remove exactly one element from the array such that max - min is minimum
    Given an array consisting of N positive integer numbers. The task is to remove exactly one element from this array to minimize max(a) - min(a) and print the minimum possible (max(a) - min(a)). Note: max(a) means largest number in array [Tex]a [/Tex]and min(a) means smallest number in array [Tex]a [/
    8 min read
  • Minimum removals from array to make max - min <= K
    Given N integers and K, find the minimum number of elements that should be removed, such that Amax-Amin<=K. After the removal of elements, Amax and Amin is considered among the remaining elements. Examples: Input : a[] = {1, 3, 4, 9, 10, 11, 12, 17, 20}, k = 4 Output : 5 Explanation: Remove 1, 3,
    15+ min read
  • Remove minimum elements from either side such that 2*min becomes more than max
    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
    15+ min read
  • Minimum elements to be removed from the ends to make the array sorted
    Given an array arr[] of length N, the task is to remove the minimum number of elements from the ends of the array to make the array non-decreasing. Elements can only be removed from the left or the right end. Examples: Input: arr[] = {1, 2, 4, 1, 5} Output: 2 We can't make the array sorted after one
    9 min read
  • Remove minimum elements from either side such that 2*min becomes more than max | Set 2
    Given an unsorted array, trim the array such that twice of minimum is greater than the maximum in the trimmed array. Elements should be removed from either end of the array. The number of removals should be minimum. Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to re
    15+ min read
  • Minimum Element for Non-Positive Array in Limited Moves
    Given the array arr[] and another integer max_moves, Find the minimum possible integer x that must be chosen such that all the elements of the array can be made non-positive in most max_moves operations. In each operation, decrease any element of the array by x. Examples: Input: n = 3, arr = [1, 2,
    14 min read
  • Maximum XOR Queries With an Element From Array
    Given an array arr[] of size n containing non-negative integers and also given a list of q queries in a 2D array queries[][], where each query is of the form [xi, mi]. For each query, you need to find the maximum value of (xi XOR arr[j]) such that arr[j] is less than or equal to mi. In simple terms,
    15+ min read
  • Minimize deletions from either end to remove Minimum and Maximum from Array
    Given array of integers arr[] of size N, the task is to find the count of minimum number of deletion operations to remove minimum and the maximum element from the array. The elements can only be deleted from either end of the array. Examples: Input: arr = [2, 10, 7, 5, 4, 1, 8, 6]Output: 5Explanatio
    7 min read
  • Find the position of the last removed element from the array
    Given an array of size [Tex]N [/Tex]and an integer [Tex]M [/Tex]. Perform the following operations on the given array: If a[i] > M then push a[i] - M to end of the array, otherwise remove it from the array.Perform the first operation while the array is non-empty. The task is to find the original
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences