Open In App

Remove all occurrences of any element for maximum array sum

Last Updated : 09 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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, and 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 the 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) time, 
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 

Algorithm:

 Step 1: Create a method named “maxSumArray” of int return type which takes an array and its length as an input parameter.          Step 2: Set the frequency of each element in the array in an unordered map called “mp” and set the integer variable “sum” to 0.
 Step 3: Run a for loop across the array repeatedly.
 Step 4: Increase the frequency of each element in the “mp” map and add it to the “sum” variable for each element in the array.
 Step 5: Set the highest possible integer value for the “minimum” integer variable.
 Step 6: Use a range-based for loop to iterate across the “mp” map.
 Step 7: Calculate the frequency and value of each element on the map, and if the result is less than the current minimum value,                  update the “minimum” variable.
 Step 8: To obtain the maximum sum after removal, deduct the “minimum” value from the “sum” variable.
 Step 9: Print the highest sum after deduction.

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)
Auxiliary Space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads