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 x such that nums remains non-empty on removing all occurrences of x.
  • Remove all occurrences of x from 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
Maximize Subarray Sum After Element RemovalInput: [1, -3, 2, 1, -3] → Find best element to remove1-321-3+1-3+2+1-3Original max subarray sum: 3 (subarray [2,1])Option 1: Remove 1-32-3Max: 2Option 2: Remove -3121Max: 4 ✓Best Strategy: Remove all -3s → Maximum sum = 4
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
Asked in
Amazon 15 Google 12 Microsoft 8
23.8K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen