
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Points by Deleting Elements from Array in Python
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] := 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 −
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 = [0] * (max_val + 1) for i in range(n) : count_list[array[i]] += 1 res = [0] * (max_val + 1) res[0] = 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