LeetCode 题解工作台

删除子数组的最大得分

给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组 。 删除子数组的 得分 就是子数组各元素之 和 。 返回 只删除一个 子数组可获得的 最大得分 。 如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],...,a[r] ,那么它就是 a 的一…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们用数组或哈希表 记录每个数字最后一次出现的位置,用前缀和数组 记录从起点到当前位置的和。我们用变量 记录当前不重复子数组的左端点。 遍历数组,对于每个数字 ,如果 存在,那么我们更新 为 $\max(j, \text{d}[v])$,这样就保证了当前不重复子数组不包含 。然后我们更新答案为 $\max(\text{ans}, \text{s}[i] - \text{s}[j])$,最…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数数组 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 <= 105
  • 1 <= nums[i] <= 104
lightbulb

解题思路

方法一:数组或哈希表 + 前缀和

我们用数组或哈希表 d\text{d} 记录每个数字最后一次出现的位置,用前缀和数组 s\text{s} 记录从起点到当前位置的和。我们用变量 jj 记录当前不重复子数组的左端点。

遍历数组,对于每个数字 vv,如果 d[v]\text{d}[v] 存在,那么我们更新 jjmax(j,d[v])\max(j, \text{d}[v]),这样就保证了当前不重复子数组不包含 vv。然后我们更新答案为 max(ans,s[i]s[j])\max(\text{ans}, \text{s}[i] - \text{s}[j]),最后更新 d[v]\text{d}[v]ii

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\text{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

删除子数组的最大得分题解:数组·哈希·扫描 | LeetCode #1695 中等