# Find the largest after deleting the given elements in C++

In this problem, we are given an array aar[] of size n and another array del[] of size m. Our task is to find the largest after deleting the given elements. If the deletion of an element with multiple instances is required, delete the first instance of the element.

Let's take an example to understand the problem,

Input : arr[] = {3, 5, 1, 7, 9, 2}, del[] = {1, 9, 3}
Output : 7

Explanation

Array arr[] after deleting the elements : {5, 7, 2}
Largest element of the array is 7

## Solution Approach

A simple solution the problem is by deleting all elements from arr[] that are present in del[]. Then sort the array in ascending order and print the last element of the array.

## Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findMaxElementDelArray(int arr[], int n, int del[], int m){
for(int i = 0; i < m; i++){
for(int j = 0; j > n; j++){
if(arr[j] == del[i]){
arr[j] = INT_MAX; break;
}
}
}
sort(arr, arr + n);
return arr[(n-m-1)];
}
int main(){
int array[] = { 3, 5, 1, 7, 9, 2 };
int m = sizeof(array) / sizeof(array[0]);
int del[] = { 1, 9, 3 };
int n = sizeof(del) / sizeof(del[0]);
cout<<"The largest element after deleting the elements is "<<findMaxElementDelArray(array, m, del, n);
return 0;
}

## Output

The largest element after deleting the elements is 7


Another Approach

A solution to the problem is using hash-map for checking deletion. We will store the elements of the del[] array to a hash map and for each element of arr[] check for its presence in hash-map. If it is present delete the element from the hash-map otherwise check if it is the maximum value by comparing it with maxVal. If yes, store it to maxVal. After the whole array arr[] is traversed print maxVal which is the maximum value after deleting elements.

## Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findMaxElementDelArray(int arr[], int m, int del[], int n){
unordered_map<int, int> delMap;
for (int i = 0; i < n; ++i) {
delMap[del[i]]++;
}
int maxVal = INT_MIN;
for (int i = 0; i < m; ++i) {
if (delMap.find(arr[i]) != delMap.end()) {
delMap[arr[i]]--;
if (delMap[arr[i]] == 0)
delMap.erase(arr[i]);
}
else
maxVal = max(maxVal, arr[i]);
}
return maxVal;
}
int main(){
int array[] = { 3, 5, 1, 7, 9, 2 };
int m = sizeof(array) / sizeof(array[0]);
int del[] = { 1, 9, 3 };
int n = sizeof(del) / sizeof(del[0]);
cout<<"The largest element after deleting the elements is "<<findMaxElementDelArray(array, m, del, n);
return 0;
}

## Output

The largest element after deleting the elements is 7


Updated on: 28-Jan-2022

122 Views