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 erasure value in Python
Suppose we have an array called nums (with positive values only) and we want to erase a subarray containing unique elements. We will get a score that is the sum of subarray elements. We have to find the maximum score we can get by erasing exactly one subarray.
So, if the input is like nums = [6,3,2,3,6,3,2,3,6], then the output will be 11, because the optimal subarray is either [6,3,2] or [2,3,6], so the sum is 11.
Algorithm
To solve this, we will follow these steps ?
- seen := a new dictionary to track element positions
- ans := maximum score, sum := current subarray sum, both initialized to 0
- l := left pointer of the sliding window
- for each index r and value x in nums, do
- if x is present in seen, then
- index := seen[x] (last position of duplicate)
- while l ≤ index, do
- remove seen[nums[l]]
- sum := sum - nums[l]
- l := l + 1
- seen[x] := r (update current position)
- sum := sum + x
- ans := maximum of ans and sum
- if x is present in seen, then
- return ans
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
seen = dict()
ans = current_sum = 0
left = 0
for right, x in enumerate(nums):
if x in seen:
index = seen[x]
while left <= index:
del seen[nums[left]]
current_sum -= nums[left]
left += 1
seen[x] = right
current_sum += x
ans = max(ans, current_sum)
return ans
nums = [6, 3, 2, 3, 6, 3, 2, 3, 6]
print(solve(nums))
The output of the above code is ?
11
How It Works
This solution uses a sliding window approach with two pointers:
- The
rightpointer expands the window by adding new elements - The
leftpointer shrinks the window when duplicates are found - The
seendictionary tracks the last position of each element - When a duplicate is encountered, we move the left pointer past the previous occurrence
Step-by-Step Trace
For nums = [6,3,2,3,6,3,2,3,6]:
- Window [6,3,2] ? sum = 11
- Next 3 is duplicate, shrink to [3] ? sum = 3
- Expand to [3,6] ? sum = 9
- Continue this process...
- Maximum sum found is 11
Conclusion
The sliding window technique efficiently finds the maximum sum subarray with unique elements in O(n) time complexity. The key insight is maintaining a window of unique elements and adjusting it when duplicates are encountered.
