- Related Questions & Answers
- Find maximum points which can be obtained by deleting elements from array in C++
- Maximum array sum that can be obtained after exactly k changes in C++
- Program to find maximum additive score by deleting numbers in Python
- Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array in C++
- Program to Find Out the Maximum Points From Removals in Python
- Check if a string can be obtained by rotating another string 2 places in Python
- Maximum Points You Can Obtain from Cards in C++
- Count of distinct sums that can be obtained by adding prime numbers from given arrays in C++
- Maximum elements which can be crossed using given units of a and b in C++
- Maximum trains for which stoppage can be provided in C++
- Find the Largest Cube formed by Deleting minimum Digits from a number in Python
- Program to find maximum sum by flipping each row elements in Python
- Check if elements of array can be made equal by multiplying given prime numbers in Python
- Find elements of an array which are divisible by N using STL in C++
- Maximum possible middle element of the array after deleting exactly k elements in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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]

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))

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

18

Advertisements