Minimize removals required to make given Array consecutive in any order
Given an array arr[]. The task is to minimize the number of removals to make all the elements in arr[] consecutive.
Examples
Input: arr[] = {45, 42, 46, 48, 47}
Output: 1
Explanation: After removing 42 we see that there is a consecutive elements present in the array(45-48).Input: arr[] = {7, 4, 8, 5, 9 }
Output: 2
Explanation: After removing 4 and 5 we see that there is a consecutive elements present in the array(7-9).
Approach: This problem can be solved by using Hashmaps. Follow the steps below to solve the given problem.
- Firstly create a map and at every element i.e at every key put its value true.
- So each element/key has true value. Now move through the keyset of the map and see if it contains (key-1) in the map.
- If it is then put false at that key.
- Now in another loop, work for that keys whose value is true and go till its longest sequence and find the length of the longest consecutive sequence.
- So the minimum number of removals will be the difference in length of array and length of the longest consecutive sequence.
Follow the steps below to solve the given problem.
Java
// Java program for above approachimport java.io.*;import java.util.*;class GFG { public static void minRemovalsConsecutive(int a[], int n) { // Hashmap to store the elements // in key-value pairs HashMap<Integer, Boolean> map = new HashMap<>(); for (int val : a) { map.put(val, true); } for (int val : map.keySet()) { if (map.containsKey(val - 1)) { map.put(val, false); } } int max = 0; // Iterating for all keys in map for (int val : map.keySet()) { if (map.get(val)) { int t1 = 1; while (map.containsKey(val + t1)) { t1++; } if (t1 > max) { max = t1; } } } // Printing the final answer System.out.println(n - max); } // Driver Code public static void main(String[] args) { int N = 5; int arr[] = { 45, 42, 46, 48, 47 }; // Function Call minRemovalsConsecutive(arr, N); }} |
Output
1
Time Complexity: O(N)
Auxiliary Space: O(N)


