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 −
Let us see the following implementation to get better understanding −
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))
[2, 4, 5, 3, 1], 2