Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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] and k = 2, then the output will be 6, as we can delete 2 and 4 from the left end.
Algorithm
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
How It Works
The algorithm uses a sliding window approach. It starts by taking the first k elements, then gradually shifts the window by removing elements from the left and adding elements from the right end. This explores all possible combinations of taking elements from both ends.
Example
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))
6
Step-by-Step Execution
For nums = [2, 4, 5, 3, 1] and k = 2 −
nums = [2, 4, 5, 3, 1]
k = 2
# Initial window: first k elements
window = sum([2, 4]) # = 6
print(f"Initial window (0 from right): {window}")
# i = 1: Remove nums[1], add nums[-1]
window = 6 - 4 + 1 # = 3
print(f"Window (1 from right): {window}")
# i = 2: Remove nums[0], add nums[-2]
window = 3 - 2 + 3 # = 4
print(f"Window (2 from right): {window}")
print(f"Maximum sum: {max(6, 3, 4)}")
Initial window (0 from right): 6 Window (1 from right): 3 Window (2 from right): 4 Maximum sum: 6
Alternative Implementation
Here's a more straightforward approach without using a class −
def max_sum_after_k_removals(nums, k):
n = len(nums)
max_sum = 0
# Try all combinations: i elements from left, (k-i) from right
for i in range(k + 1):
left_sum = sum(nums[:i]) if i > 0 else 0
right_sum = sum(nums[n-(k-i):]) if k-i > 0 else 0
current_sum = left_sum + right_sum
max_sum = max(max_sum, current_sum)
return max_sum
# Test the function
nums = [2, 4, 5, 3, 1]
k = 2
result = max_sum_after_k_removals(nums, k)
print(f"Maximum sum: {result}")
Maximum sum: 6
Conclusion
The sliding window approach efficiently finds the maximum sum by exploring all possible combinations of removing elements from both ends. The time complexity is O(k) and space complexity is O(1).
