- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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

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

- Related Articles
- Program to find maximum score from removing stones in Python
- Program to find maximum sum by performing at most k negate operations in Python
- Program to find maximum sum of multiplied numbers in Python
- Find sum by removing first character from a string followed by numbers in MySQL?
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to count maximum score from removing substrings 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 k-repeating substring from sequence in Python
- Program to find maximum additive score by deleting numbers in Python
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Program to find maximum sum by flipping each row elements in Python
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Program to find maximum value by inserting operators in between numbers in Python
- Program to Find K-Largest Sum Pairs in Python

Advertisements