Given an array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of it and delete all occurrences of Ai-1 and Ai+1 (if they exist) in the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.
Note: We have to delete all the occureneces of Ai+1 and Ai-1 elements if they are present in the array and not Ai+1 and Ai-1.
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 and we are left with {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.
Our aim is to maximize the sum of selected numbers. The idea is to pre-calculate the occurrence of all numbers x in the array a[] in a hash ans. Now our recurrence relation will decide either to select a number or not. If we select the number then we take the occurrences of that number and the value stored at ans[i-2] as ans[i-1] will be deleted and not be taken to count. If we do not select the number then we take ans[i-1] which have been pre-calculated while moving forward.
ans[i] = max(ans[i-1], ans[i-2] + ans[i]*i )
At the end, ans[maximum] will have the maximum sum of selected numbers.
Below is the implementation of above idea:
C++
// CPP program to Maximize the sum of selected// numbers by deleting three consecutive numbers.#include <bits/stdc++.h>using namespace std;// function to maximize the sum of selected numbersint maximizeSum(int a[], int n) { // stores the occurrences of the numbers unordered_map<int, int> ans; // marks the occurrence of every number in the sequence for (int i = 0; i < n; i++) ans[a[i]]++; // maximum in the sequence int maximum = *max_element(a, a + n); // traverse till maximum and apply the recurrence relation for (int i = 2; i <= maximum; i++) ans[i] = max(ans[i - 1], ans[i - 2] + ans[i] * i); // return the ans stored in the index of maximum return ans[maximum];}// Driver codeint main() { int a[] = {1, 2, 3}; int n = sizeof(a) / sizeof(a[0]); 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 nummbers//by deleting occurences of Ai-1 and Ai+1static 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 occurence of each element int []ans = new int[max + 1]; for(int i = 0; i < n; i++) { ans[arr[i]]++; } // Using the above mentioned approach for(int i = 2; i <= max; i++) { ans[i] = Math.max(ans[i - 1], ans[i - 2] + i* ans[i]); } return ans[max]; } // Driver code public static void main(String[] args) { int []a = {1, 2, 3}; System.out.println(getMaximumSum(a)); } } // This code is contributed by Sooraj Kumar (NITS CSE 2020) |
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) : # 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 # maximum in the sequence maximum = max(a) # traverse till maximum and apply # the recurrence relation for i in range(2, maximum + 1) : ans[i] = max(ans[i - 1], ans[i - 2] + ans[i] * i) # return the ans stored in the # index of maximum return ans[maximum] # 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;class GFG { // Function to maximise the sum of selected nummbers //by deleting occurences 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 = -1; for(int i = 0; i < n; i++) { max = Math.Max(max, arr[i]); } // An array to count the occurence of each element int []ans = new int[max + 1]; for(int i = 0; i < n; i++) { ans[arr[i]]++; } // Using the above mentioned approach for(int i = 2; i <= max; i++) { ans[i] = Math.Max(ans[i - 1], ans[i - 2] + i* ans[i]); } return ans[max]; } // Driver code public static void Main(string[] args) { int []a = {1, 2, 3}; Console.Write(getMaximumSum(a)); } } // This code is contributed by rock_cool |
Output:
4
Time Complexity: O(Amax), where Amax is the maximum element present in the array A[].
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Maximize cost to empty an array by removing contiguous subarrays of equal elements
- Minimum palindromic subarray removals to make array Empty
- Maximum sum such that exactly half of the elements are selected and no two adjacent
- Maximize the numbers of splits in an Array having sum divisible by 3
- Maximize sum of remaining elements after every removal of the array half with greater sum
- Modify array to maximize sum of adjacent differences
- Remove array end element to maximize the sum of product
- Maximize the sum of array after multiplying a prefix and suffix by -1
- Reverse a subarray to maximize sum of even-indexed elements of given array
- Maximize the Sum of a Subsequence from an Array based on given conditions
- Maximize Sum possible from an Array by the given moves
- Maximize sum of an Array by flipping sign of all elements of a single subarray
- Maximize the subarray sum after multiplying all elements of any subarray with X
- Maximize sum by choosing elements from different section of a matrix
- Maximize product of digit sum of consecutive pairs in a subsequence of length K
- Maximize sum of topmost elements of S stacks by popping at most N elements
- Maximize sum of all elements which are not a part of the Longest Increasing Subsequence
- Maximize sum of pairwise products generated from the given Arrays
- Maximize array elements upto given number
- Remove an element to maximize the GCD of the given array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

