LeetCode 1695. 删除子数组的最大得分

1695. 删除子数组的最大得分

给你一个正整数数组 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 <= 10^5
  • 1 <= nums[i] <= 10^4

提示 1

The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements.


提示 2

This can be solved using the two pointers technique

 

解法:滑动窗口

class Solution {
    public int maximumUniqueSubarray(int[] nums) {
        int ans = Integer.MIN_VALUE;
        int sum = 0;
        Map<Integer, Integer> window = new HashMap<>();
        int left = 0;
        int right = 0;
        while (right < nums.length) {
            sum += nums[right];
            window.merge(nums[right], 1, Integer::sum);
            while (window.get(nums[right]) > 1) {
                window.merge(nums[left], -1, Integer::sum);
                sum -= nums[left];
                left++;
            }
            ans = Math.max(ans, sum);
            right++;
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(n),n 是 数组 nums 的长度。
  • 空间复杂度:O(n)。

 

另一种写法:

class Solution {
    public int maximumUniqueSubarray(int[] nums) {
        int ans = Integer.MIN_VALUE;
        int sum = 0;
        Map<Integer, Integer> window = new HashMap<>();
        int left = 0;
        int right = 0;
        while (right < nums.length) {
            while (window.containsKey(nums[right])) {
                window.remove(nums[left]);
                sum -= nums[left];
                left++;
            }

            window.put(nums[right], 1);
            sum += nums[right];
            ans = Math.max(ans, sum);
            right++;
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(n),n 是 数组 nums 的长度。
  • 空间复杂度:O(n)。
  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值