# Program to Find Out the Maximum Points From Removals 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 are provided with a list of positive numbers. Now, here we can remove any contiguous sub list of some length t with the same value and get points t * t. One condition is to be considered, that we can perform this any number of times until the list is empty. So we have to determine the maximum number of points we can get.

So, if the input is like nums = [4, 4, 6, 4, 4], then the output will be 17.

For the output, we can first remove the 6 which has length 1 and yields 1 * 1 = 1 point. Then we can take the list [4, 4, 4, 4] which has length 4 and yields 4 * 4 = 16 points. So finally, we can get 17 points.

To solve this, we will follow these steps −

• Define a function dp() . This will take left, right, t

• if left > right is non−zero, then

• return 0

• num := nums[left]

• left2 := left

• while left2 < right and nums[left2 + 1] is same as num, do

• left2 := left2 + 1

• t := t + left2 − left + 1

• left := left2 + 1

• points := t to the power 2 + dp(left, right, 0)

• for mid in range left to right + 1, do

• if nums[mid] is same as num, then

• points := maximum of (points, dp(left, mid − 1, 0) + dp(mid, right, t))

• return points

• From the main function, we do the following −

• print(dp(0, size of nums − 1, 0))

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums):
def dp(left, right, t):
if left > right:
return 0
num = nums[left]
left2 = left
while left2 < right and nums[left2 + 1] == num:
left2 += 1
t += left2 − left + 1
left = left2 + 1
points = t ** 2 + dp(left, right, 0)
for mid in range(left, right + 1):
if nums[mid] == num:
points = max(points, dp(left, mid − 1, 0) + dp(mid, right, t))
return points
return dp(0, len(nums) − 1, 0)
ob1 = Solution()
print(ob1.solve([4, 4, 6, 4, 4]))

## Input

[4, 4, 6, 4, 4]

## Output

17