Open In App

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

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

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 <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum sum of
// selected numbers from an array to make
// the array empty
int maximizeSum(vector<int> 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[1] = freq[1]
    dp[1] = freq[1];
  
    // 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 Code
int main()
{
    vector<int> arr = {2, 2, 3, 3, 3, 4};
  
    // Function Call
    cout << (maximizeSum(arr));
}
  
// This code is contributed by amreshkumar3.


Java




// java program for the above approach
class 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[1] = freq[1]
        dp[1] = freq[1];
  
        // 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 empty
def 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 = [0] * (max(arr)+1)
  
    # Loop to iterate over array arr[]
    for i in arr:
        freq[i] += 1
  
    # Stores the DP states
    dp = [0] * (max(arr)+1)
  
    # Initially dp[1] = freq[1]
    dp[1] = freq[1]
  
    # 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 Code
arr = [2, 2, 3, 3, 3, 4]
  
# Function Call
print(maximizeSum(arr))


C#




// C# program for the above approach
using 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[1] = freq[1]
        dp[1] = freq[1];
  
        // 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




<script>
      // JavaScript Program to implement
      // the above approach
 
      // Function to find the maximum sum of
      // selected numbers from an array to make
      // the array empty
      function maximizeSum(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
          let freq = new Array(Math.max(...arr) + 1).fill(0);
 
          // Loop to iterate over array arr[]
          for (let i = 0; i < arr.length; i++)
              freq[arr[i]] += 1
 
          // Stores the DP states
          let dp = new Array(Math.max(...arr) + 1).fill(0);
 
 
          // Initially dp[1] = freq[1]
          dp[1] = freq[1]
 
          // Iterate over the range [2, MAX]
          for (let i = 2; i <= Math.max(...arr) + 1; i++)
              dp[i] = Math.max(freq[i] * i + dp[i - 2], dp[i - 1])
 
          // Return Answer
          return dp[(Math.max(...arr))]
      }
      // Driver Code
      let arr = [2, 2, 3, 3, 3, 4]
 
      // Function Call
      document.write(maximizeSum(arr))
        
   // This code is contributed by Potta Lokesh
 
  </script>


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.



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

Similar Reads