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 Removing One Element INPUT nums array: 1 [0] -3 [1] 2 [2] 1 [3] -3 [4] Unique elements to try removing: x=1 x=-3 x=2 Prefix sums (left to right): 0 1 -2 0 1 Suffix sums (right to left): -2 -3 0 -2 -3 ALGORITHM STEPS 1 Compute prefix max sums Track max subarray ending at i 2 Compute suffix max sums Track max subarray starting at i 3 Try removing each x Skip positions where nums[i]=x 4 Connect prefix + suffix Max = prefix[i-1] + suffix[j+1] Example: Remove x = -3 Original: 1 -3 2 1 -3 After: 1 2 1 Sum: 1 + 2 + 1 = 4 FINAL RESULT Max subarray sum for each x: Remove x Max Sum x = 1 2 x = -3 4 x = 2 2 none 2 OUTPUT 4 OK - Maximum achieved by removing all -3 values Optimal subarray: [1, 2, 1] Key Insight: Using prefix and suffix maximum subarray sums, we can efficiently compute the best result after removing all occurrences of any element x. When we skip positions with value x, we connect the best prefix ending before x with the best suffix starting after x. Time complexity: O(n * k) where k = unique elements. TutorialsPoint - Maximize Subarray Sum After Removing All Occurrences of One Element | Optimized with Prefix/Suffix Sums
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