Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array nums.
You can do the following operation on the array at most once:
x such that nums remains non-empty on removing all occurrences of x.x from the array.Return the maximum subarray sum across all possible resulting arrays.
Example 1:
Input: nums = [-3,2,-2,-1,3,-2,3]
Output: 7
Explanation:
We can have the following arrays after at most one operation:
nums = [-3, 2, -2, -1, 3, -2, 3]. The maximum subarray sum is 3 + (-2) + 3 = 4.x = -3 results in nums = [2, -2, -1, 3, -2, 3]. The maximum subarray sum is 3 + (-2) + 3 = 4.x = -2 results in nums = [-3, 2, -1, 3, 3]. The maximum subarray sum is 2 + (-1) + 3 + 3 = 7.x = -1 results in nums = [-3, 2, -2, 3, -2, 3]. The maximum subarray sum is 3 + (-2) + 3 = 4.x = 3 results in nums = [-3, 2, -2, -1, -2]. The maximum subarray sum is 2.The output is max(4, 4, 7, 4, 2) = 7.
Example 2:
Input: nums = [1,2,3,4]
Output: 10
Explanation:
It is optimal to not perform any operations.
Constraints:
1 <= nums.length <= 105-106 <= nums[i] <= 106Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Segment Tree
[-3,2,-2,-1,3,-2,3]
[1,2,3,4]
maximum-subarray)maximum-subarray-sum-with-one-deletion)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
class Solution {
public long maxSubarraySum(int[] nums) {
long ans = Arrays.stream(nums).max().getAsInt();
long prefix = 0;
long minPrefix = 0;
// the minimum prefix sum that can have a negative number removed
long modifiedMinPrefix = 0;
Map<Integer, Integer> count = new HashMap<>();
// minPrefixPlusRemoval[num] := the minimum prefix sum plus removed `num`
Map<Integer, Long> minPrefixPlusRemoval = new HashMap<>();
for (int num : nums) {
prefix += num;
ans = Math.max(ans, prefix - modifiedMinPrefix);
if (num < 0) {
count.merge(num, 1, Integer::sum);
minPrefixPlusRemoval.put(
num, Math.min(minPrefixPlusRemoval.getOrDefault(num, 0L), minPrefix) + num);
modifiedMinPrefix = Math.min(modifiedMinPrefix,
Math.min(count.get(num) * num, minPrefixPlusRemoval.get(num)));
}
minPrefix = Math.min(minPrefix, prefix);
modifiedMinPrefix = Math.min(modifiedMinPrefix, minPrefix);
}
return ans;
}
}
// Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
package main
import (
"math"
"math/bits"
"slices"
)
// https://space.bilibili.com/206214
func maxSubarraySum(nums []int) int64 {
ans := math.MinInt
var s, nonDelMinS, allMin int
delMinS := map[int]int{}
for _, x := range nums {
s += x
ans = max(ans, s-allMin)
if x < 0 {
delMinS[x] = min(delMinS[x], nonDelMinS) + x
allMin = min(allMin, delMinS[x])
nonDelMinS = min(nonDelMinS, s)
}
}
return int64(ans)
}
func maxSubarraySumPS(nums []int) int64 {
n := len(nums)
f := math.MinInt / 2
s := 0
last := map[int]int{}
update := func(x int) int {
res := f // f[i-1]
f = max(f, 0) + x // f[i] = max(f[i-1], 0) + x
if v, ok := last[x]; ok {
res = max(res, v+s) // s[i]
}
s += x // s[i+1] = s[i] + x
last[x] = res - s
return res
}
pre := make([]int, n)
for i, x := range nums {
pre[i] = update(x)
}
ans := math.MinInt
f = math.MinInt / 2
s = 0
clear(last)
for i, x := range slices.Backward(nums) {
suf := update(x)
ans = max(ans, f, pre[i]+suf, pre[i], suf)
}
return int64(ans)
}
//
type info struct {
ans, sum, pre, suf int
}
type seg []info
func (t seg) set(o, val int) {
t[o] = info{val, val, val, val}
}
func (t seg) mergeInfo(a, b info) info {
return info{
max(max(a.ans, b.ans), a.suf+b.pre),
a.sum + b.sum,
max(a.pre, a.sum+b.pre),
max(b.suf, b.sum+a.suf),
}
}
func (t seg) maintain(o int) {
t[o] = t.mergeInfo(t[o<<1], t[o<<1|1])
}
// 初始化线段树
func (t seg) build(nums []int, o, l, r int) {
if l == r {
t.set(o, nums[l])
return
}
m := (l + r) >> 1
t.build(nums, o<<1, l, m)
t.build(nums, o<<1|1, m+1, r)
t.maintain(o)
}
// 单点更新
func (t seg) update(o, l, r, i, val int) {
if l == r {
t.set(o, val)
return
}
m := (l + r) >> 1
if i <= m {
t.update(o<<1, l, m, i, val)
} else {
t.update(o<<1|1, m+1, r, i, val)
}
t.maintain(o)
}
// 区间询问(没用到)
func (t seg) query(o, l, r, L, R int) info {
if L <= l && r <= R {
return t[o]
}
m := (l + r) >> 1
if R <= m {
return t.query(o<<1, l, m, L, R)
}
if m < L {
return t.query(o<<1|1, m+1, r, L, R)
}
return t.mergeInfo(t.query(o<<1, l, m, L, R), t.query(o<<1|1, m+1, r, L, R))
}
func maxSubarraySumSeg(nums []int) int64 {
n := len(nums)
t := make(seg, 2<<bits.Len(uint(n-1)))
t.build(nums, 1, 0, n-1)
ans := t[1].ans // 不删任何数
if ans <= 0 {
return int64(ans)
}
pos := map[int][]int{}
for i, x := range nums {
if x < 0 {
pos[x] = append(pos[x], i)
}
}
for _, idx := range pos {
for _, i := range idx {
t.update(1, 0, n-1, i, 0) // 删除
}
ans = max(ans, t[1].ans)
for _, i := range idx {
t.update(1, 0, n-1, i, nums[i]) // 复原
}
}
return int64(ans)
}
# Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
class Solution:
def maxSubarraySum(self, nums: list[int]) -> int:
ans = max(nums)
prefix = 0
minPrefix = 0
# the minimum prefix sum that can have a negative number removed
modifiedMinPrefix = 0
count = collections.Counter()
# minPrefixPlusRemoval[num] := the minimum prefix sum plus removed `num`
minPrefixPlusRemoval = {}
for num in nums:
prefix += num
ans = max(ans, prefix - modifiedMinPrefix)
if num < 0:
count[num] += 1
minPrefixPlusRemoval[num] = (
min(minPrefixPlusRemoval.get(num, 0), minPrefix) + num)
modifiedMinPrefix = min(modifiedMinPrefix,
count[num] * num,
minPrefixPlusRemoval[num])
minPrefix = min(minPrefix, prefix)
modifiedMinPrefix = min(modifiedMinPrefix, minPrefix)
return ans
// Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
// class Solution {
// public long maxSubarraySum(int[] nums) {
// long ans = Arrays.stream(nums).max().getAsInt();
// long prefix = 0;
// long minPrefix = 0;
// // the minimum prefix sum that can have a negative number removed
// long modifiedMinPrefix = 0;
// Map<Integer, Integer> count = new HashMap<>();
// // minPrefixPlusRemoval[num] := the minimum prefix sum plus removed `num`
// Map<Integer, Long> minPrefixPlusRemoval = new HashMap<>();
//
// for (int num : nums) {
// prefix += num;
// ans = Math.max(ans, prefix - modifiedMinPrefix);
// if (num < 0) {
// count.merge(num, 1, Integer::sum);
// minPrefixPlusRemoval.put(
// num, Math.min(minPrefixPlusRemoval.getOrDefault(num, 0L), minPrefix) + num);
// modifiedMinPrefix = Math.min(modifiedMinPrefix,
// Math.min(count.get(num) * num, minPrefixPlusRemoval.get(num)));
// }
// minPrefix = Math.min(minPrefix, prefix);
// modifiedMinPrefix = Math.min(modifiedMinPrefix, minPrefix);
// }
//
// return ans;
// }
// }
// Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3410: Maximize Subarray Sum After Removing All Occurrences of One Element
// class Solution {
// public long maxSubarraySum(int[] nums) {
// long ans = Arrays.stream(nums).max().getAsInt();
// long prefix = 0;
// long minPrefix = 0;
// // the minimum prefix sum that can have a negative number removed
// long modifiedMinPrefix = 0;
// Map<Integer, Integer> count = new HashMap<>();
// // minPrefixPlusRemoval[num] := the minimum prefix sum plus removed `num`
// Map<Integer, Long> minPrefixPlusRemoval = new HashMap<>();
//
// for (int num : nums) {
// prefix += num;
// ans = Math.max(ans, prefix - modifiedMinPrefix);
// if (num < 0) {
// count.merge(num, 1, Integer::sum);
// minPrefixPlusRemoval.put(
// num, Math.min(minPrefixPlusRemoval.getOrDefault(num, 0L), minPrefix) + num);
// modifiedMinPrefix = Math.min(modifiedMinPrefix,
// Math.min(count.get(num) * num, minPrefixPlusRemoval.get(num)));
// }
// minPrefix = Math.min(minPrefix, prefix);
// modifiedMinPrefix = Math.min(modifiedMinPrefix, minPrefix);
// }
//
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.