# Maximize the sum of selected numbers from an array to make it empty

• Difficulty Level : Hard
• Last Updated : 28 Mar, 2022

Given an array A[] of N numbers, we need to maximize the sum of selected numbers following the given operation:

• At each step, you need to select a number Ai, delete one occurrence and add it to the sum.
• Delete one occurrence of Ai-1 and Ai+1 (if they exist in the array).
• Repeat these steps until the array gets empty.

Examples:

Input: A[] = {1, 2, 3}
Output: 4
Explanation: At first step we select 1, so 1 and 2 are deleted from the sequence leaving us with 3.
Then we select 3 from the sequence and delete it.
So the sum of selected numbers is 1+3 = 4.

Input: A[] =  {1, 2, 2, 2, 3, 4}
Output: 10
Explanation: Select one of the 2’s from the array.
So  2, 2-1, 2+1 will be deleted.
Now array is {2, 2, 4}, since 1 and 3 are deleted.
Select 2 in next two steps, and then select 4 in the last step.
We get a sum of 2 + 2 + 2 + 4 = 10 which is the maximum possible.

Approach: The idea to solve the problem is:

Pre-calculate the occurrence of all numbers ( say x ) in the array A[] and then iterate from maximum number to minimum number.
For each number x delete one occurrence of x and x-1(if exists) and add x to the sum until x is completely removed.

Follow the steps mentioned below to solve the problem

• Calculate the MAX value in the array.
• Create an array of size MAX and store the occurrences of each element in it.
• Since we want to maximize our answer, we will start iterating from the MAX value to 0.
• If the occurrence of the ith element is greater than 0, then add it to our answer decrease the occurrences of the i-1th element by 1, and also decrease the occurrence of ith by 1 since we have added it to our answer.
• We don’t have to decrease the occurrence of the i+1th element because we are already starting from the end so i+1th is already processed.
• There might be multiple occurrences of the ith element that’s why do not decrease i yet, to stay on the same element.

Below is the implementation of the above idea:

## C++

 `// CPP program to Maximize the sum of selected``// numbers by deleting three consecutive numbers.``#include ``using` `namespace` `std;` `// function to maximize the sum of selected numbers``int` `maximizeSum(``int` `arr[], ``int` `n) {` `      ``// Largest element in the array``    ``int` `mx = -1;``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``mx = max(mx, arr[i]);``    ``}   ``    ` `    ``// An array to count the occurrence of each element``    ``int` `freq[mx + 1];``    ` `    ``memset``(freq, 0, ``sizeof``(freq));``    ` `    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``freq[arr[i]]++;``    ``}``    ` `    ``// ans to store the result``    ``int` `ans = 0, i=mx;``    ` `    ``// Using the above mentioned approach``    ``while``(i>0){``        ` `        ``// if occurrence is greater than 0``        ``if``(freq[i] > 0){``            ``// add it to ans``            ``ans += i;``            ` `            ``// decrease i-1th element by 1``            ``freq[i-1]--;``            ` `            ``// decrease ith element by 1``            ``freq[i]--;``        ``}``else``{``            ``// decrease i``            ``i--;``        ``}       ``    ``}``    ` `    ``return` `ans;``}` `// Driver code``int` `main()``{``  ``int` `a[] = {1, 2, 3};``  ``int` `n = ``sizeof``(a) / ``sizeof``(a);``  ``cout << maximizeSum(a, n);``  ``return` `0;``}`

## Java

 `// Java implementation of the approach``import` `java.util.*;``import` `java.math.*;` `class` `GFG``{``      ``// Function to maximise the sum of selected numbers``      ``//by deleting occurrences of Ai-1 and Ai+1``    ``public` `static` `int` `getMaximumSum (``int` `arr[]) {``        ` `        ``// Number of elements in the array``        ``int` `n = arr.length;``        ` `        ``// Largest element in the array``        ``int` `max = -``1``;``        ``for``(``int` `i = ``0``; i < n; i++)``        ``{``            ``max = Math.max(max, arr[i]);``        ``}``        ` `        ``// An array to count the occurrence of each element``        ``int` `[]freq = ``new` `int``[max + ``1``];``        ` `        ``for``(``int` `i = ``0``; i < n; i++)``        ``{``            ``freq[arr[i]]++;``        ``}``        ` `        ``// ans to store the result``        ``int` `ans = ``0``, i=max;``        ` `        ``// Using the above mentioned approach``        ``while``(i>``0``){``            ` `            ``// if occurrence is greater than 0``            ``if``(freq[i] > ``0``){``                ``// add it to ans``                ``ans += i;``                ` `                ``// decrease i-1th element by 1``                ``freq[i-``1``]--;``                ` `                ``// decrease ith element by 1``                ``freq[i]--;``            ``}``else``{               ``                ``// decrease i``                ``i--;``            ``}           ``        ``}``        ` `        ``return` `ans;``    ``}` `      ``// Driver code``      ``public` `static` `void` `main(String[] args)``      ``{``          ``int` `[]a = {``1``, ``2``, ``3``};` `          ``System.out.println(getMaximumSum(a));``      ``}``}`

## Python3

 `# Python3 program to Maximize the sum of selected``# numbers by deleting three consecutive numbers.` `# function to maximize the sum of``# selected numbers``def` `maximizeSum(a, n) :` `        ``# maximum in the sequence``    ``maximum ``=` `max``(a)``    ` `    ``# stores the occurrences of the numbers``    ``ans ``=` `dict``.fromkeys(``range``(``0``, n ``+` `1``), ``0``)` `    ``# marks the occurrence of every``    ``# number in the sequence``    ``for` `i ``in` `range``(n) :``        ``ans[a[i]] ``+``=` `1``        ` `    ``# ans to store the result``    ``result ``=` `0``    ``i ``=` `maximum``    ` `    ``# Using the above mentioned approach``    ``while` `i > ``0``:``        ` `        ``# if occurrence is greater than 0``        ``if` `ans[i] > ``0``:``            ``# add it to ans``            ``result ``+``=` `i;``            ` `            ``# decrease i-1th element by 1``            ``ans[i``-``1``] ``-``=` `1``;``            ` `            ``# decrease ith element by 1``            ``ans[i] ``-``=` `1``;``        ``else``:          ``            ``# decrease i``            ``i ``-``=` `1``;``    ` `    ``return` `result;` `# Driver code``if` `__name__ ``=``=` `"__main__"` `:` `    ``a ``=` `[``1``, ``2``, ``3``]``    ``n ``=` `len``(a)``    ``print``(maximizeSum(a, n))` `# This code is contributed by Ryuga`

## C#

 `// C# implementation of the approach``using` `System;``using` `System.Linq;` `class` `GFG``{` `// Function to maximise the sum of selected numbers``//by deleting occurrences of Ai-1 and Ai+1``static` `int` `getMaximumSum(``int` `[]arr)``{``    ``// Number of elements in the array``    ``int` `n = arr.Length;` `    ``// Largest element in the array``    ``int` `max = arr.Max();` `    ``// An array to count the occurrence of each element``    ``int` `[]freq = ``new` `int``[max + 1];` `    ``for``(``int` `j = 0; j < n; j++)``    ``{``      ``freq[arr[j]]++;``    ``}` `    ``// ans to store the result``    ``int` `ans = 0, i=max;` `    ``// Using the above mentioned approach``    ``while``(i>0){` `      ``// if occurrence is greater than 0``      ``if``(freq[i] > 0){``        ``// add it to ans``        ``ans += i;` `        ``// decrease i-1th element by 1``        ``freq[i-1]--;` `        ``// decrease ith element by 1``        ``freq[i]--;``      ``}``else``{               ``        ``// decrease i``        ``i--;``      ``}           ``    ``}` `    ``return` `ans;``}` `// Driver code``public` `static` `void` `Main(``string``[] args)``{``    ``int` `[]a = {1, 2, 3};` `    ``Console.Write(getMaximumSum(a));``}``}` `// This code is contributed by rock_cool`

## Javascript

 ``

Output:

`4`

Time Complexity: (Amax + Highest occurrence of element in arr), because if the frequency is greater than 1 then we are processing that element multiple times.
Auxiliary Space: O(Amax ), where Amax is the maximum element present in array A[].

My Personal Notes arrow_drop_up