# Find maximum points which can be obtained by deleting elements from array in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array A with N elements, we also have two integers l and r where, 1≤ ax ≤ 10^5 and 1≤ l≤ r≤ N. Taking an element from the array say ax and remove it, and also remove all elements equal to ax+1, ax+2 … ax+R and ax-1, ax-2 … ax-L from that array. By doing this it will cost ax points. We have to maximize the total cost after removing all of the elements from the array.

So, if the input is like A = [2,4,3,10,5], l = 1, r = 2, then the output will be 18.

To solve this, we will follow these steps −

• n := size of array

• max_val := 0

• for i in range 0 to n, do

• max_val := maximum of max_val, array[i]

• count_list := an array of size (max_val + 1), fill with 0

• for i in range 0 to n, do

• count_list[array[i]] := count_list[array[i]] + 1

• res := an array of size (max_val + 1), fill with 0

• res := 0

• left := minimum of left, right

• for num in range 1 to max_val + 1, do

• k := maximum of num - left - 1, 0

• res[num] := maximum of res[num - 1], num * count_list[num] + res[k]

• return res[max_val]

## Example

Let us see the following implementation to get better understanding −

Live Demo

def get_max_cost(array, left, right) :
n = len(array)
max_val = 0
for i in range(n) :
max_val = max(max_val, array[i])
count_list =  * (max_val + 1)
for i in range(n) :
count_list[array[i]] += 1
res =  * (max_val + 1)
res = 0
left = min(left, right)
for num in range(1, max_val + 1) :
k = max(num - left - 1, 0)
res[num] = max(res[num - 1], num * count_list[num] + res[k])
return res[max_val]
array = [2,4,3,10,5]
left = 1
right = 2
print(get_max_cost(array, left, right))

## Input

[2,4,3,10,5] , 1, 2

## Output

18