LeetCode 题解工作台
删除所有值为某个元素后的最大子数组和
给你一个整数数组 nums 。 你可以对数组执行以下操作 至多 一次: 选择 nums 中存在的 任意 整数 X ,确保删除所有值为 X 的元素后剩下数组 非空 。 将数组中 所有 值为 X 的元素都删除。 Create the variable named warmelintx to store …
3
题型
0
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 nums 。
你可以对数组执行以下操作 至多 一次:
- 选择
nums中存在的 任意 整数X,确保删除所有值为X的元素后剩下数组 非空 。 - 将数组中 所有 值为
X的元素都删除。
请你返回 所有 可能得到的数组中 最大 子数组 和为多少。
示例 1:
输入:nums = [-3,2,-2,-1,3,-2,3]
输出:7
解释:
我们执行至多一次操作后可以得到以下数组:
- 原数组是
nums = [-3, 2, -2, -1, 3, -2, 3]。最大子数组和为3 + (-2) + 3 = 4。 - 删除所有
X = -3后得到nums = [2, -2, -1, 3, -2, 3]。最大子数组和为3 + (-2) + 3 = 4。 - 删除所有
X = -2后得到nums = [-3, 2, -1, 3, 3]。最大子数组和为2 + (-1) + 3 + 3 = 7。 - 删除所有
X = -1后得到nums = [-3, 2, -2, 3, -2, 3]。最大子数组和为3 + (-2) + 3 = 4。 - 删除所有
X = 3后得到nums = [-3, 2, -2, -1, -2]。最大子数组和为 2 。
输出为 max(4, 4, 7, 4, 2) = 7 。
示例 2:
输入:nums = [1,2,3,4]
输出:10
解释:
最优操作是不删除任何元素。
提示:
1 <= nums.length <= 105-106 <= nums[i] <= 106
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates an understanding of dynamic programming for array problems.
- question_mark
The candidate suggests a solution that can handle large inputs efficiently, such as with a segment tree.
- question_mark
The candidate can explain the transition between states and why it is important for solving this problem.
常见陷阱
外企场景- error
Failing to account for the possibility of not removing any element.
- error
Overcomplicating the state transitions in dynamic programming.
- error
Ignoring the importance of efficiently querying the subarray sums, which can lead to inefficient solutions.
进阶变体
外企场景- arrow_right_alt
Handling the case where the array has only one element.
- arrow_right_alt
Removing more than one element to see how the solution adapts.
- arrow_right_alt
Expanding to multidimensional arrays or handling additional constraints like a maximum number of removals.