- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

6

- Related Questions & Answers
- Find sum by removing first character from a string followed by numbers in MySQL?
- Program to find maximum k-repeating substring from sequence in Python
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- Program to find maximum additive score by deleting numbers in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find maximum sum by flipping each row elements in Python
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Program to Find K-Largest Sum Pairs in Python
- Program to find maximum value by inserting operators in between numbers in Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find maximum time to finish K tasks in Python
- Program to find maximum ascending subarray sum using Python
- Python program to find the maximum of three numbers
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find sum of rectangle whose sum at most k in Python

Advertisements