Maximum score of deleting an element from an Array based on given condition
Last Updated :
15 Jul, 2025
Given an array arr[], the task is to find the maximum score of deleting an element where each element of the array can be deleted with the score of the element, but the constraint is if we delete arr[i], then arr[i] + 1 and arr[i] - 1 is gets automatically deleted with 0 scores.
Examples:
Input: arr[] = {7, 2, 1, 8, 3, 3, 6, 6}
Output: 27
Explanation:
Step 0: arr[] = 7 2 1 8 3 3 6 6, Score: 0
Step 1: arr[] = 7 1 8 3 6 6, Score: 3
Step 2: arr[] = 7 1 8 6 6, Score: 6
Step 3: arr[] = 7 8 6 6, Score: 7
Step 4: arr[] = 8 6, Score: 13
Step 5: arr[] = 8 Score: 19
Step 6: arr[] = [] Score: 27
Input: arr[] = 1 2 3
Output: 4
Approach: The idea is to use Dynamic Programming to solve this problem. The key observation of the problem is that for removing any element from the array the occurrence of the element and the value itself is the important factor.
Let's take an example to understand the observation if the sequence was 4 4 5. Then, we have two choices to choose from 4 to 5. Now, on choosing 4, his score would be 4*2 = 8. On the other hand, if we choose 5, his score would be 5*1 = 5. Clearly, the maximal score is 8.
Hence, for the above sequence 4 4 5, freq[4] = 2, and freq[5] = 1.
Finally, to find the optimal score, it would be easy to first break the problem down into a smaller problem. In this case, we break the sequence into smaller sequences and find an optimal solution for it. For the sequence of numbers containing only 0, the answer would be 0. Similarly, if a sequence contains only the number 0 and 1, then the solution would be count[1]*1.
Recurrence Relation:
dp[i] = max(dp[i - 1], dp[i - 2] + i*freq[i])
Basically, we have 2 cases, either to pick an ith element and other is not to pick an ith element.
Case 1: If we pick the ith element, Maximum score till the ith element will be dp[i-2] + i*freq[i] (choosing ith element means deleting (i-1)th element)
Case 2: If we don't pick the ith element, the Maximum Score till ith element will dp[i-1]
Now as We have to maximize the score, We will take the maximum of both.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// maximum score of the deleting a
// element from an array
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum
// score of the deleting an element
// from an array
int findMaximumScore(vector<int> a, int n)
{
// Creating a map to keep
// the frequency of numbers
unordered_map<int, int> freq;
// Loop to iterate over the
// elements of the array
for (int i = 0; i < n; i++) {
freq[a[i]]++;
}
// Creating a DP array to keep
// count of max score at ith element
// and it will be filled
// in the bottom Up manner
vector<int> dp(*max_element(a.begin(),
a.end())
+ 1,
0);
dp[0] = 0;
dp[1] = freq[1];
// Loop to choose the elements of the
// array to delete from the array
for (int i = 2; i < dp.size(); i++)
dp[i] = max(
dp[i - 1],
dp[i - 2] + freq[i] * i);
return dp[dp.size() - 1];
}
// Driver Code
int main()
{
int n;
n = 3;
vector<int> a{ 1, 2, 3 };
// Function Call
cout << findMaximumScore(a, n);
return 0;
}
Java
// Java implementation to find the
// maximum score of the deleting a
// element from an array
import java.util.*;
class GFG{
// Function to find the maximum
// score of the deleting an element
// from an array
static int findMaximumScore(int []a, int n)
{
// Creating a map to keep
// the frequency of numbers
@SuppressWarnings("unchecked")
HashMap<Integer,
Integer> freq = new HashMap();
// Loop to iterate over the
// elements of the array
for(int i = 0; i < n; i++)
{
if(freq.containsKey(a[i]))
{
freq.put(a[i],
freq.get(a[i]) + 1);
}
else
{
freq.put(a[i], 1);
}
}
// Creating a DP array to keep
// count of max score at ith element
// and it will be filled
// in the bottom Up manner
int []dp = new int[Arrays.stream(a).max().getAsInt() + 1];
dp[0] = 0;
dp[1] = freq.get(1);
// Loop to choose the elements of the
// array to delete from the array
for(int i = 2; i < dp.length; i++)
dp[i] = Math.max(dp[i - 1],
dp[i - 2] +
freq.get(i) * i);
return dp[dp.length - 1];
}
// Driver Code
public static void main(String[] args)
{
int n;
n = 3;
int []a = { 1, 2, 3 };
// Function call
System.out.print(findMaximumScore(a, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation to find the
# maximum score of the deleting a
# element from an array
from collections import defaultdict
# Function to find the maximum
# score of the deleting an element
# from an array
def findMaximumScore(a, n):
# Creating a map to keep
# the frequency of numbers
freq = defaultdict (int)
# Loop to iterate over the
# elements of the array
for i in range (n):
freq[a[i]] += 1
# Creating a DP array to keep
# count of max score at ith element
# and it will be filled
# in the bottom Up manner
dp = [0] * (max(a) + 1)
dp[0] = 0
dp[1] = freq[1]
# Loop to choose the elements of the
# array to delete from the array
for i in range (2, len(dp)):
dp[i] = max(dp[i - 1],
dp[i - 2] +
freq[i] * i)
return dp[- 1]
# Driver Code
if __name__ == "__main__":
n = 3
a = [1, 2, 3]
# Function Call
print(findMaximumScore(a, n))
# This code is contributed by Chitranayal
C#
// C# implementation to find the
// maximum score of the deleting a
// element from an array
using System;
using System.Linq;
using System.Collections.Generic;
class GFG{
// Function to find the maximum
// score of the deleting an element
// from an array
static int findMaximumScore(int []a, int n)
{
// Creating a map to keep
// the frequency of numbers
Dictionary<int,
int> freq = new Dictionary<int,
int>();
// Loop to iterate over the
// elements of the array
for(int i = 0; i < n; i++)
{
if(freq.ContainsKey(a[i]))
{
freq[a[i]] = freq[a[i]] + 1;
}
else
{
freq.Add(a[i], 1);
}
}
// Creating a DP array to keep
// count of max score at ith element
// and it will be filled
// in the bottom Up manner
int []dp = new int[a.Max() + 1];
dp[0] = 0;
dp[1] = freq[1];
// Loop to choose the elements of the
// array to delete from the array
for(int i = 2; i < dp.Length; i++)
dp[i] = Math.Max(dp[i - 1],
dp[i - 2] +
freq[i] * i);
return dp[dp.Length - 1];
}
// Driver Code
public static void Main(String[] args)
{
int n;
n = 3;
int []a = { 1, 2, 3 };
// Function call
Console.Write(findMaximumScore(a, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript implementation to find the
// maximum score of the deleting a
// element from an array
// Function to find the maximum
// score of the deleting an element
// from an array
function findMaximumScore(a,n)
{
// Creating a map to keep
// the frequency of numbers
let freq = new Map();
// Loop to iterate over the
// elements of the array
for(let i = 0; i < n; i++)
{
if(freq.has(a[i]))
{
freq.set(a[i],
freq.get(a[i]) + 1);
}
else
{
freq.set(a[i], 1);
}
}
// Creating a DP array to keep
// count of max score at ith element
// and it will be filled
// in the bottom Up manner
let dp = new Array(Math.max(...a)+1);
dp[0] = 0;
dp[1] = freq.get(1);
// Loop to choose the elements of the
// array to delete from the array
for(let i = 2; i < dp.length; i++)
dp[i] = Math.max(dp[i - 1],
dp[i - 2] +
freq.get(i) * i);
return dp[dp.length - 1];
}
// Driver Code
let n = 3;
let a=[1, 2, 3];
// Function call
document.write(findMaximumScore(a, n));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Another Approach Using Memoization:
C++
// C++ implementation to find the
// maximum score of the deleting a
// element from an array
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum
// score of the deleting an element
// from an array
int solve(vector<int> &arr, int i)
{
if(i >= arr.size()) // if i is greater than size of array
{
return 0; // then simply returnn zero
}
// current 'i' on which we are standing
int currValue = arr[i]; // current value
int currSum = arr[i]; // intial make sum as same as value
int index = i + 1; // index to take elemets, so i + 1
// while it is the same as the current value, include in our sum
while(index < arr.size() && arr[index] == currValue)
{
currSum += arr[i];
index++;
}
// Now, we have to skip all the elements, whose value is equal to
// currValue + 1
while(index < arr.size() && arr[index] == currValue + 1)
{
index++;
}
//And lastly, we have two choices-
//whether to include the sum of this current element
// in our answer
// or not include the sum of current element in our answer
// so we explore all possibility and take maximum of them
return max(currSum + solve(arr, index), solve(arr, i + 1));
// If we decide to take the curr element in our answer, then upto the
// elemet we skip the next value, we paas that index
// but if decided no to make this vurrent element then simply paas
// i + 1
}
int findMaximumScore(vector<int>& arr) {
int n = arr.size(); // take the size of the array
// sort the array to get rid of all arr[i] - 1 elements
sort(arr.begin(), arr.end());
// solve function which give us our final answer
return solve(arr, 0);
// ↑
// we start from zero index
}
// Driver Code
int main()
{
int n;
n = 3;
vector<int> a{ 1, 2, 3 };
// Function Call
cout << findMaximumScore(a);
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Main {
// Function to find the maximum score of deleting an
// element from an array
static int solve(ArrayList<Integer> arr, int i)
{
if (i >= arr.size()) // if i is greater than size of array
{
return 0;
}
// current 'i' on which we are standing
int currValue = arr.get(i);
int currSum = arr.get(i);
int index = i + 1;
// while it is the same as the current value, include in our sum
while (index < arr.size()
&& arr.get(index) == currValue) {
currSum += arr.get(i);
index++;
}
// Now, we have to skip all the elements, whose value is equal to
// currValue + 1
while (index < arr.size()
&& arr.get(index) == currValue + 1) {
index++;
}
//And lastly, we have two choices-
//whether to include the sum of this current element
// in our answer
// or not include the sum of current element in our answer
// so we explore all possibility and take maximum of them
return Math.max(currSum + solve(arr, index),
solve(arr, i + 1));
}
// If we decide to take the curr element in our answer, then upto the
// elemet we skip the next value, we paas that index
// but if decided no to make this vurrent element then simply paas
// i + 1
static int findMaximumScore(ArrayList<Integer> arr)
{
int n = arr.size();
// sort the array to get rid of all arr[i] - 1 elements
Collections.sort(arr);
return solve(arr, 0);
}
// Driver Code
public static void main(String[] args)
{
int n = 3;
ArrayList<Integer> a
= new ArrayList<>(Arrays.asList(1, 2, 3));
// Function Call
System.out.println(findMaximumScore(a));
}
}
Python
def solve(arr, i):
# Base case: if i is greater than or equal to the size of the array, return 0
if i >= len(arr):
return 0
currValue = arr[i] # current value at index i
currSum = arr[i] # initialize the current sum as the current value
index = i + 1 # index to take elements, starting from i + 1
# While the elements have the same value as the current value, include them in our sum
while index < len(arr) and arr[index] == currValue:
currSum += arr[i]
index += 1
# Now, we have to skip all the elements whose value is equal to currValue + 1
while index < len(arr) and arr[index] == currValue + 1:
index += 1
# Lastly, we have two choices - whether to include the sum of the current element in our answer
# or not include the sum of the current element in our answer. So, we explore all possibilities and take the maximum of them
return max(currSum + solve(arr, index), solve(arr, i + 1))
def find_maximum_score(arr):
arr.sort() # Sort the array to get rid of all arr[i] - 1 elements
# Call the solve function to get our final answer, starting from index 0
return solve(arr, 0)
# Driver Code
if __name__ == "__main__":
arr = [1, 2, 3]
print(find_maximum_score(arr))
C#
// C# implementation to find the
// maximum score of the deleting a
// element from an array
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Function to find the maximum score by combining
// adjacent elements in the list
static int Solve(List<int> arr, int i)
{
// Base case: if we reach the end of the list,
// return 0
if (i >= arr.Count) {
return 0;
}
// Initialize variables to keep track of the current
// value, current sum, and next index
int currValue = arr[i];
int currSum = arr[i];
int index = i + 1;
// Calculate the sum of adjacent elements with the
// same value
while (index < arr.Count
&& arr[index] == currValue) {
currSum += arr[i];
index++;
}
// Skip elements that have a value of "currValue +
// 1" and move to the next unique value
while (index < arr.Count
&& arr[index] == currValue + 1) {
index++;
}
// Return the maximum score by either choosing the
// current element and recursively calling the
// function for the next unique element or skipping
// the current element and calling the function for
// the next element.
return Math.Max(currSum + Solve(arr, index),
Solve(arr, i + 1));
}
// Function to find the maximum score by first sorting
// the list and then calling Solve
static int FindMaximumScore(List<int> arr)
{
arr.Sort(); // Sort the list in ascending order
return Solve(arr,
0); // Start the recursive calculation
// from the beginning of the list
}
static void Main()
{
List<int> a = new List<int>{ 1, 2, 3 };
// Find the maximum score and print the result
Console.WriteLine(FindMaximumScore(a));
}
}
JavaScript
// Function to recursively find the maximum score of
// deleting an element from an array
function solve(arr, i) {
if (i >= arr.length) {
return 0;
}
// current 'i' on which we are standing
let currValue = arr[i]; // current value
let currSum = arr[i]; // initialize sum as the current value
let index = i + 1; // index to take elements, so i + 1
// while the element is the same as the current value, include
// it in our sum
while (index < arr.length && arr[index] === currValue) {
currSum += arr[i];
index++;
}
// Now, we have to skip all the elements whose value is equal
// to currValue + 1
while (index < arr.length && arr[index] === currValue + 1) {
index++;
}
// Explore two choices:
// 1. Include the sum of the current element in our answer
// and move to the next unique element (index).
// 2. Exclude the current element from our answer and move
// to the next element (i + 1).
// Take the maximum of these two possibilities.
return Math.max(currSum + solve(arr, index), solve(arr, i + 1));
}
// Function to find the maximum score of deleting an element from
// an array
function findMaximumScore(arr) {
const n = arr.length;
// Sort the array in ascending order to get rid of all arr[i] - 1
// elements
arr.sort((a, b) => a - b);
// Call the solve function to get the final answer
return solve(arr, 0);
// ↑
// Start from the zero index
}
// Driver Code
const a = [1, 2, 3];
console.log(findMaximumScore(a));
Time complexity: O(n)
Auxiliary Space: O(m)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem