Maximize sum of selected numbers from Array to empty it | Set 2

• Last Updated : 17 Jan, 2022

Given an array arr[] of N integers, the task is to maximize the sum of selected numbers over all the operations such that in each operation, choose a number Ai, delete one occurrence of it and delete all occurrences of Ai – 1 and Ai + 1 (if they exist) in the array until the array gets empty.

Examples:

Input: arr[] = {3, 4, 2}
Output: 6
Explanation: In 1st operation, select 4 and delete it. Therefore, all occurrences of 3 and 5 are deleted from arr[]. The array after the operation is arr[] = {2}. In 2nd operation select 2. Hence, the sum of all selected numbers = 4+2 = 6 which is the maximum possible.

Input: arr[] = {2, 2, 3, 3, 3, 4}
Output: 9
Explanation: In 1st operation, select 3 and delete it. Therefore, all occurrences of 2 and 4 are deleted from arr[]. The array after the operation is arr[] = {3, 3}. In 2nd and 3rd operation select 3. Hence, the sum of all selected numbers = 3+3+3 = 9, which is the maximum possible.

Approach: The given problem can be solved by counting the frequency of array elements and then find the maximum sum which is discussed in the previous post of this article.

Time Complexity: O(M + F), where M is the maximum element of the array and F is the maximum frequency of an array element.
Auxiliary Space: O(M), where M is the maximum element of the array.

Dynamic Programming Approach:  The above approach can also be optimized and solved using Dynamic Programming. It can be observed that if a number Ai of the array arr[] is selected, it will contribute Ai * freq[Ai] into the final sum. Using this observation, follow the below steps to solve the given problem:

• Create an array freq[], which stores the frequency of each element in the array arr[].
• Create a 1D array dp[], where dp[i] represents the maximum possible sum of the selected values that lie in the range [1, i] in the given array.
• For each value of i, there are two possible cases as follows:
• Case 1, where i is selected. In this case, the value of dp[i] = freq[i] * i + dp[i-2].
• Case 2, where i – 1 is selected. In this case, the value of dp[i] = dp[i-1].
• Therefore, the DP relation of the above problem is:

dp[i] = max( dp[i – 1], (freq[i] * i)+ dp[i – 2]) for all values of i in range [0, MAX] where MAX is the maximum integer in arr[]

• The value stored in dp[MAX] is the required answer.

Below is the implementation of the above approach:

C++

 // cpp program for the above approach#include using namespace std; // Function to find the maximum sum of// selected numbers from an array to make// the array emptyint maximizeSum(vector arr){     // Edge Case    if (arr.size() == 0)        return 0;     // Stores the frequency of each element    // in the range [0, MAX] where MAX is    // the maximum integer in the array arr     int mx= *max_element(arr.begin(),arr.end());    int freq[mx + 1]={0};     // Loop to iterate over array arr[]    for (int i : arr)        freq[i] += 1;     // Stores the DP states    int dp[mx + 1]={0};     // Initially dp = freq    dp = freq;     // Iterate over the range [2, MAX]    for (int i = 2; i < mx + 1; i++)        dp[i] = max(freq[i] * i + dp[i - 2],                    dp[i - 1]);     // Return Answer    return dp[mx];} // Driver Codeint main(){    vector arr = {2, 2, 3, 3, 3, 4};     // Function Call    cout << (maximizeSum(arr));} // This code is contributed by amreshkumar3.

Java

 // java program for the above approachclass GFG{       // Utility function to find    // maximum value of an element in array    static int getMax(int [] arr)    {        int max = Integer.MIN_VALUE;                 for(int i = 0; i < arr.length; i++)        {           if(arr[i] > max)             max = arr[i];        }                 return max;           }       // Function to find the maximum sum of    // selected numbers from an array to make    // the array empty    static int maximizeSum(int [] arr)    {         // Edge Case        if (arr.length == 0)            return 0;         // Stores the frequency of each element        // in the range [0, MAX] where MAX is        // the maximum integer in the array arr             int max = getMax(arr);        int [] freq = new int[max + 1];         // Loop to iterate over array arr[]        for (int i : arr)          freq[i] += 1;         // Stores the DP states        int[] dp = new int[max + 1];         // Initially dp = freq        dp = freq;         // Iterate over the range [2, MAX]        for (int i = 2; i < max + 1; i++)            dp[i] = Math.max(freq[i] * i + dp[i - 2],                             dp[i - 1]);         // Return Answer        return dp[max];    }     // Driver Code    public static void main(String [] args)    {        int [] arr = { 2, 2, 3, 3, 3, 4 };         // Function Call        System.out.println((maximizeSum(arr)));    }} // This code is contributed by AR_Gaurav

Python3

 # Python program for the above approach # Function to find the maximum sum of# selected numbers from an array to make# the array emptydef maximizeSum(arr):     # Edge Case    if not arr:        return 0     # Stores the frequency of each element    # in the range [0, MAX] where MAX is    # the maximum integer in the array arr    freq =  * (max(arr)+1)     # Loop to iterate over array arr[]    for i in arr:        freq[i] += 1     # Stores the DP states    dp =  * (max(arr)+1)     # Initially dp = freq    dp = freq     # Iterate over the range [2, MAX]    for i in range(2, max(arr)+1):        dp[i] = max(freq[i]*i + dp[i-2], dp[i-1])     # Return Answer    return dp[max(arr)] # Driver Codearr = [2, 2, 3, 3, 3, 4] # Function Callprint(maximizeSum(arr))

C#

 // C# program for the above approachusing System;using System.Linq;class GFG{       // Function to find the maximum sum of    // selected numbers from an array to make    // the array empty    static int maximizeSum(int[] arr)    {         // Edge Case        if (arr.Length == 0)            return 0;         // Stores the frequency of each element        // in the range [0, MAX] where MAX is        // the maximum integer in the array arr        int[] freq = new int[(arr.Max() + 1)];         // Loop to iterate over array arr[]        foreach(int i in arr) freq[i] += 1;         // Stores the DP states        int[] dp = new int[(arr.Max() + 1)];         // Initially dp = freq        dp = freq;         // Iterate over the range [2, MAX]        for (int i = 2; i < arr.Max() + 1; i++)            dp[i] = Math.Max(freq[i] * i + dp[i - 2],                             dp[i - 1]);         // Return Answer        return dp[arr.Max()];    }     // Driver Code    public static void Main()    {        int[] arr = { 2, 2, 3, 3, 3, 4 };         // Function Call        Console.WriteLine((maximizeSum(arr)));    }} // This code is contributed by ukasp.

Javascript


Output:
9

Time Complexity: O(M + F), where M is the maximum element of the array.
Auxiliary Space: O(M), where M is the maximum element of the array.

My Personal Notes arrow_drop_up