LeetCode 2461.长度为K子数组中的最大和
题目:
给你一个整数数组 nums
和一个整数 k
。请你从 nums
中满足下述条件的全部子数组中找出最大子数组和:
- 子数组的长度是
k
,且 - 子数组中的所有元素 各不相同 。
返回满足题面要求的最大子数组和。如果不存在子数组满足这些条件,返回 0
。
子数组 是数组中一段连续非空的元素序列。
思路:定长滑动窗口 hashmap
代码:
class Solution {public long maximumSubarraySum(int[] nums, int k) {Map<Integer, Integer> map = new HashMap<>();long ans = 0;long sum = 0;for (int i = 0; i < nums.length; i++) {sum += nums[i];map.merge(nums[i], 1, Integer::sum);if (i - k + 1 < 0) {continue;}if (map.size() == k) {ans = Math.max(ans, sum);}int out = nums[i - k + 1];int c = map.get(out);if (c > 1) {map.put(out, c - 1);} else {map.remove(out);}sum -= out;}return ans;}
}
性能: