Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Remove an occurrence of most frequent array element exactly K times
Next article icon

Remove all occurrences of any element for maximum array sum

Last Updated : 09 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Remove an occurrence of most frequent array element exactly K times

S

Sairahul Jella
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Searching
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash
  • Searching

Similar Reads

  • Minimum sum possible by removing all occurrences of any array element
    Given an array arr[] consisting of N integers, the task is to find the minimum possible sum of the array by removing all occurrences of any single array element. Examples: Input: N = 4, arr[] = {4, 5, 6, 6}Output: 9Explanation: All distinct array elements are {4, 5, 6}. Removing all occurrences of 4
    6 min read
  • Remove an occurrence of most frequent array element exactly K times
    Given an array arr[], the task is to remove an occurrence of the most frequent array element exactly K times. If multiple array elements have maximum frequency, remove the smallest of them. Print the K deleted elements. Examples: Input: arr[] = {1, 3, 2, 1, 4, 1}, K = 2Output: 1 1Explanation: The fr
    12 min read
  • Find the sum of all highest occurring elements in an Array
    Given an array of integers containing duplicate elements. The task is to find the sum of all highest occurring elements in the given array. That is the sum of all such elements whose frequency is maximum in the array.Examples: Input : arr[] = {1, 1, 2, 2, 2, 2, 3, 3, 3, 3} Output : 20 The highest oc
    6 min read
  • Maximise occurrence of an element after K replacements within Array elements
    Given an array arr[] having N integers, and an integer K, the task is to find an array such that it contains a single elements maximum number of times possible after K replacements within array elements. Examples: Input: N = 7, arr[] = {1, 2, 1, 5, 1, 6, 7}, K = 3Output: {1, 1, 1, 1, 1, 1, 7}Explana
    7 min read
  • Maximum sum of increasing order elements from n arrays
    Given n arrays of size m each. Find the maximum sum obtained by selecting a number from each array such that the elements selected from the i-th array are more than the element selected from (i-1)-th array. If maximum sum cannot be obtained then return 0.Examples: Input : arr[][] = {{1, 7, 3, 4}, {4
    13 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Sum of maximum elements of all subsets
    Given an array of integer numbers, we need to find sum of maximum number of all possible subsets. Examples: Input : arr = {3, 2, 5}Output : 28Explanation : Subsets and their maximum are,{} maximum = 0{3} maximum = 3{2} maximum = 2{5} maximum = 5{3, 2} maximum = 3{3, 5} maximum = 5{2, 5} maximum = 5{
    9 min read
  • Maximum possible sum of non-adjacent array elements not exceeding K
    Given an array arr[] consisting of N integers and an integer K, the task is to select some non-adjacent array elements with the maximum possible sum not exceeding K. Examples: Input: arr[] = {50, 10, 20, 30, 40}, K = 100Output: 90Explanation: To maximize the sum that doesn't exceed K(= 100), select
    15 min read
  • Maximum subarray sum possible after removing at most K array elements
    Given an array arr[] of size N and an integer K, the task is to find the maximum subarray sum by removing at most K elements from the array. Examples: Input: arr[] = { -2, 1, 3, -2, 4, -7, 20 }, K = 1 Output: 26 Explanation: Removing arr[5] from the array modifies arr[] to { -2, 1, 3, -2, 4, 20 } Su
    15+ min read
  • Maximum Subarray sum of A[] by adding any element of B[] at any end
    Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it: Choose either the leftmost or rightmost
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences