Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the k largest numbers after deleting the given elements in C++
In this problem, we are given an array arr[] of size n, array del[] of size m, and an integer k. Our task is to find the k largest numbers after deleting the given elements.
We need to print the first k largest elements from the array arr[] found after deleting all elements present in the del[] array. If two instances are present in the array delete the first instance.
Let's take an example to understand the problem,
Input : arr[] = {3, 5, 1, 7, 9, 2}, del[] = {1, 9, 3}, k = 2
Output : 7, 5
Explanation −
Array arr[] after deleting the elements : {5, 7, 2}
2 maximum elements are 7, 5.
Solution Approach
A simple solution the problem is by deleting all elements from arr[] that are present in del[]. Then sort the array in descending order and print first k elements of the array.
Example
Program to illustrate the working of our solution
#includeusing namespace std; void findKmaxElementDelArray(int arr[], int n, int del[], int m, int k){ for(int i = 0; i ()); for (int i = 0; i Output
2 largest numbers after deleting the elements are 7 5Another approach
Another approach to solve the problem is using hashmap and heap. We will create a max-heap and a hash map. The hashmap will contain all the elements of the array del[]. And then insert elements of the array arr[] that are not present in hash-map to the max-heap. Pop k elements from the heap and then print it.
Example
Program to illustrate the working of our solution
#includeusing namespace std; void findKmaxElementDelArray(int arr[], int n, int del[], int m, int k){ unordered_map deleteElement; for (int i = 0; i maxHeap; for (int i = 0; i Output
2 largest numbers after deleting the elements are 7 5
