Skip to content
Related Articles

Related Articles

Improve Article

Remove all occurrences of any element for maximum array sum

  • Difficulty Level : Hard
  • Last Updated : 27 May, 2021

Given an array of positive integers, remove all the occurrences of the element to get the maximum sum of the remaining array.

Examples: 

Input : arr = {1, 1, 3} 
Output : 3 
On removing 1 from the array, we get {3}. The total value is 3

Input : arr = {1, 1, 3, 3, 2, 2, 1, 1, 1} 
Output : 11 
On removing 2 from the array, we get {1, 1, 3, 3, 1, 1, 1}. The total value is 11. 

The Brute Force solution is to first find the sum of an array, after that, find all the frequencies of the elements in the array. Find the value contributed by them to the array sum. Select the minimum value among them. To get the maximum sum of the array after removing is the equal difference of the total value of the sum and minimum value contributed by the individual element’s total frequent value.
Time complexity: O(n2)



A better approach We first find the total sum of the array and then sort the array, count the individual frequencies while traversing the array and get the maximum value. After sorting, we can use frequencies of all elements in O(n) tine, 
The time complexity of this approach is O(n Log n)

An Efficient Approach is to use hashing to count the frequencies of elements while traversing the array. Find the minimum value using the frequencies stored in the array 

C++




#include <bits/stdc++.h>
using namespace std;
 
int maxSumArray(int arr[], int n)
{
    // Find total sum and frequencies of elements
    int sum = 0;
    unordered_map<int, int> mp;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        mp[arr[i]]++;
    }
 
    // Find minimum value to be subtracted.
    int minimum = INT_MAX;
    for (auto x : mp)
        minimum = min(minimum, x.second * x.first);
 
    // Find maximum sum after removal
    return (sum - minimum);
}
 
// Drivers code
int main()
{
    int arr[] = { 1, 1, 3, 3, 2, 2, 1, 1, 1 };
    int n = sizeof(arr) / sizeof(int);
    cout << maxSumArray(arr, n);
    return 0;
}

Java




// Java program to convert fractional decimal
// to binary number
import java.util.*;
 
class GFG
{
 
static int maxSumArray(int arr[], int n)
{
    // Find total sum and frequencies of elements
    int sum = 0;
    Map<Integer,Integer> m = new HashMap<>();
    for (int i = 0 ; i < n; i++)
    {
        sum += arr[i];
        if(m.containsKey(arr[i]))
        {
            m.put(arr[i], m.get(arr[i])+1);
        }
        else
        {
            m.put(arr[i], 1);
        }
    }
     
    // Find minimum value to be subtracted.
    int minimum = Integer.MAX_VALUE;
    for (Map.Entry<Integer,Integer> x : m.entrySet())
        minimum = Math.min(minimum, x.getValue() * x.getKey());
 
    // Find maximum sum after removal
    return (sum - minimum);
}
 
// Drivers code
public static void main(String[] args)
{
    int arr[] = { 1, 1, 3, 3, 2, 2, 1, 1, 1 };
    int n = arr.length;
    System.out.println(maxSumArray(arr, n));
}
}
 
// This code contributed by Rajput-Ji

Python3




# Python3 program to convert
# fractional decimal to binary number
from sys import maxsize
def maxSumArray(arr, n):
     
    # Find total sum and frequencies of elements
    sum1 = 0
    mp = {i:0 for i in range(4)}
    for i in range(n):
        sum1 += arr[i]
        mp[arr[i]] += 1
 
    # Find minimum value to be subtracted.
    minimum = maxsize
    for key, value in mp.items():
        if(key == 0):
            continue
        minimum = min(minimum, value * key)
 
    # Find maximum sum after removal
    return (sum1 - minimum)
 
# Driver Code
if __name__ =='__main__':
    arr = [1, 1, 3, 3, 2, 2, 1, 1, 1]
    n = len(arr)
    print(maxSumArray(arr, n))
     
# This code is contributed by
# Surendra_Gangwar

C#




// C# program to convert fractional decimal
// to binary number
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int maxSumArray(int []arr, int n)
{
    // Find total sum and frequencies of elements
    int sum = 0;
    Dictionary<int,int> m = new Dictionary<int,int>();
    for (int i = 0 ; i < n; i++)
    {
        sum += arr[i];
        if(m.ContainsKey(arr[i]))
        {
            var val = m[arr[i]];
            m.Remove(arr[i]);
            m.Add(arr[i], val + 1);
        }
        else
        {
            m.Add(arr[i], 1);
        }
    }
     
    // Find minimum value to be subtracted.
    int minimum = int.MaxValue;
    foreach(KeyValuePair<int, int> x in m)
        minimum = Math.Min(minimum, (x.Value * x.Key));
 
    // Find maximum sum after removal
    return (sum - minimum);
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 1, 3, 3, 2, 2, 1, 1, 1 };
    int n = arr.Length;
    Console.WriteLine(maxSumArray(arr, n));
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
function maxSumArray(arr, n)
{
    // Find total sum and frequencies of elements
    var sum = 0;
    var mp = new Map();
    for (var i = 0; i < n; i++) {
        sum += arr[i];
        if(mp.has(arr[i]))
            mp.set(arr[i], mp.get(arr[i])+1)
        else   
            mp.set(arr[i], 1)
    }
 
    // Find minimum value to be subtracted.
    var minimum = 1000000000;
    mp.forEach((value, key) => {
        minimum = Math.min(minimum, value * key);
    });
 
    // Find maximum sum after removal
    return (sum - minimum);
}
 
// Drivers code
var arr = [1, 1, 3, 3, 2, 2, 1, 1, 1];
var n = arr.length;
document.write( maxSumArray(arr, n));
 
</script>
Output: 
11

 

Time complexity: O(n)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :