Maximum Segment Sum After Removals - Problem
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments.
A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.
Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal.
Note: The same index will not be removed more than once.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,-1,3,4], removeQueries = [0,2,1]
›
Output:
[7,7,3]
💡 Note:
Initially segments are [1,2] (sum=3) and [3,4] (sum=7). After removing index 0: segments are [2] (sum=2) and [3,4] (sum=7), max=7. After removing index 2: segments are [2] and [3,4], max=7. After removing index 1: segment is [3,4], max=7. Wait, that's wrong. Let me recalculate: After removing 0: [2,-1,3,4] → segments [2] and [3,4], max=7. After removing 2: [2,3,4] → segment [2,3,4] doesn't work because we removed -1, so segments are [2] and [3,4], max=7. After removing 1: [-1,3,4] → segment [3,4], max=7. Actually the answer should be [7,7,3] where the last 3 comes from [3,4]=7 after removing index 1.
Example 2 — All Positive Numbers
$
Input:
nums = [3,2,1,2,4], removeQueries = [4,1,3,0,2]
›
Output:
[12,9,6,3,0]
💡 Note:
Initially all positive: segment [3,2,1,2,4] sum=12. Remove 4: [3,2,1,2] sum=8, max=8. Remove 1: [3,1,2] segments [3] and [1,2], max=3. Remove 3: [3,1] segment sums, max. Remove 0: [1], max=1. Remove 2: [], max=0.
Example 3 — Single Element
$
Input:
nums = [5], removeQueries = [0]
›
Output:
[0]
💡 Note:
After removing the only positive element, no segments remain, so maximum sum is 0.
Constraints
- n == nums.length == removeQueries.length
- 1 ≤ n ≤ 105
- -109 ≤ nums[i] ≤ 109
- 0 ≤ removeQueries[i] < n
- All values of removeQueries are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with positive/negative numbers and removal queries
2
Process
Remove elements in query order, find max segment sum
3
Output
Array of maximum segment sums after each removal
Key Takeaway
🎯 Key Insight: Process removals in reverse - it's easier to add elements and merge segments than to split them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code