LeetCode 题解工作台
删除子数组的最大得分
给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组 。 删除子数组的 得分 就是子数组各元素之 和 。 返回 只删除一个 子数组可获得的 最大得分 。 如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],...,a[r] ,那么它就是 a 的一…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用数组或哈希表 记录每个数字最后一次出现的位置,用前缀和数组 记录从起点到当前位置的和。我们用变量 记录当前不重复子数组的左端点。 遍历数组,对于每个数字 ,如果 存在,那么我们更新 为 $\max(j, \text{d}[v])$,这样就保证了当前不重复子数组不包含 。然后我们更新答案为 $\max(\text{ans}, \text{s}[i] - \text{s}[j])$,最…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组。删除子数组的 得分 就是子数组各元素之 和 。
返回 只删除一个 子数组可获得的 最大得分 。
如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],...,a[r] ,那么它就是 a 的一个子数组。
示例 1:
输入:nums = [4,2,4,5,6] 输出:17 解释:最优子数组是 [2,4,5,6]
示例 2:
输入:nums = [5,2,1,2,5,2,1,2,5] 输出:8 解释:最优子数组是 [5,2,1] 或 [1,2,5]
提示:
1 <= nums.length <= 1051 <= nums[i] <= 104
解题思路
方法一:数组或哈希表 + 前缀和
我们用数组或哈希表 记录每个数字最后一次出现的位置,用前缀和数组 记录从起点到当前位置的和。我们用变量 记录当前不重复子数组的左端点。
遍历数组,对于每个数字 ,如果 存在,那么我们更新 为 ,这样就保证了当前不重复子数组不包含 。然后我们更新答案为 ,最后更新 为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
d = [0] * (max(nums) + 1)
s = list(accumulate(nums, initial=0))
ans = j = 0
for i, v in enumerate(nums, 1):
j = max(j, d[v])
ans = max(ans, s[i] - s[j])
d[v] = i
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate implement a sliding window efficiently with hash lookups?
- question_mark
Does the candidate demonstrate the ability to optimize space and time complexity using hash maps?
- question_mark
How well does the candidate handle edge cases like arrays with minimal or repetitive values?
常见陷阱
外企场景- error
Failing to handle duplicate values correctly when adjusting the window.
- error
Not updating the sum efficiently after modifying the sliding window.
- error
Overcomplicating the solution with unnecessary nested loops or extra space.
进阶变体
外企场景- arrow_right_alt
What if the array contains only one element?
- arrow_right_alt
How would the solution change if the elements in the array were sorted?
- arrow_right_alt
What if the problem required finding the maximum product instead of the sum?