Program to find maximum sum by removing K numbers from ends in python

Suppose we have a list of numbers called nums and another value k. We have to find the maximum sum of elements that we can delete, given that we must pop exactly k times, where each pop can be from the left or the right end.

So, if the input is like nums = [2, 4, 5, 3, 1] k = 2, then the output will be 6, as we can delete 2 and the 4.

To solve this, we will follow these steps −

• window := sum of all numbers from index 0 through k - 1
• ans := window
• for i in range 1 to k, do
• window := window - nums[k - i]
• window := window + nums[-i]
• ans := maximum of ans and window
• return ans

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, nums, k):
window = sum(nums[:k])
ans = window
for i in range(1, k + 1):
window -= nums[k - i]
window += nums[-i]
ans = max(ans, window)
return ans
ob = Solution()
nums = [2, 4, 5, 3, 1]
k = 2
print(ob.solve(nums, k))

Input

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

Output

6