Maximize Subarray Sum After Removing All Occurrences of One Element - Problem
You are given an integer array nums. You can do the following operation on the array at most once:
- Choose any integer
xsuch thatnumsremains non-empty on removing all occurrences ofx. - Remove all occurrences of
xfrom the array.
Return the maximum subarray sum across all possible resulting arrays.
A subarray is a contiguous part of an array.
Input & Output
Example 1 — Remove Negative Elements
$
Input:
nums = [1, -3, 2, 1, -3]
›
Output:
4
💡 Note:
Remove all occurrences of -3 to get [1, 2, 1]. The maximum subarray sum is 1 + 2 + 1 = 4.
Example 2 — Remove Positive Elements
$
Input:
nums = [1, -3, -4, 2]
›
Output:
2
💡 Note:
We can remove -3 to get [1, -4, 2] (max sum = 2), or remove -4 to get [1, -3, 2] (max sum = 2), or remove 1 to get [-3, -4, 2] (max sum = 2). Best result is 2.
Example 3 — All Elements Same
$
Input:
nums = [5, 5, 5, 5]
›
Output:
15
💡 Note:
Cannot remove all 5s (array must remain non-empty). Original array has max subarray sum of 5+5+5+5 = 20. But we must remove at least one occurrence. Actually, we don't have to remove any element, so answer is 20. Wait - re-reading: we can do the operation "at most once", meaning 0 or 1 times. So answer is 20.
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
- The resulting array must be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original array with positive and negative elements
2
Try Removals
Test removing each unique element
3
Best Result
Find the removal that gives maximum subarray sum
Key Takeaway
🎯 Key Insight: Remove elements that break up positive sequences or contribute large negative values to maximize the resulting subarray sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code