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

When we delete an element from an array, we might need to remove related elements as well. This problem asks us to find the maximum points we can obtain by strategically deleting elements, where deleting an element ax gives us ax points but also forces us to remove elements in the range [ax-L, ax+R].

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

Algorithm Steps

To solve this, we will follow these steps ?

  • Find the maximum value in the array

  • Create a frequency count array for all possible values

  • Use dynamic programming to find the optimal selection

  • For each value, decide whether to include it or skip it

  • Consider the constraint that selecting a value removes nearby values

Implementation

Let us see the following implementation to get better understanding ?

def get_max_cost(array, left, right):
    n = len(array)
    max_val = 0
    
    # Find maximum value in array
    for i in range(n):
        max_val = max(max_val, array[i])
    
    # Count frequency of each element
    count_list = [0] * (max_val + 1)
    for i in range(n):
        count_list[array[i]] += 1
    
    # Dynamic programming array
    res = [0] * (max_val + 1)
    res[0] = 0
    left = min(left, right)
    
    # For each possible value, decide to include or exclude
    for num in range(1, max_val + 1):
        k = max(num - left - 1, 0)
        # Either skip this number or include it with its count
        res[num] = max(res[num - 1], num * count_list[num] + res[k])
    
    return res[max_val]

# Test the function
array = [2, 4, 3, 10, 5]
left = 1
right = 2
result = get_max_cost(array, left, right)
print(f"Maximum points: {result}")
Maximum points: 18

How It Works

The algorithm uses dynamic programming where res[i] represents the maximum points we can get considering elements from 1 to i. For each element, we have two choices:

  • Skip the element: Take the result from the previous element (res[num-1])

  • Include the element: Add all occurrences of this element (num * count_list[num]) plus the best result from before the conflict range (res[k])

Example Walkthrough

For array [2,4,3,10,5] with l=1, r=2:

  • If we select 10, we get 10 points but must remove elements in range [8,12]

  • If we select 2, we get 2 points but must remove elements in range [0,4]

  • The optimal strategy gives us 18 points total

Conclusion

This dynamic programming solution efficiently finds the maximum points by considering the trade-off between including high-value elements and the constraint of removing nearby elements. The time complexity is O(max_val) where max_val is the largest element in the array.

Updated on: 2026-03-25T09:45:50+05:30

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements