返回介绍

solution / 2400-2499 / 2461.Maximum Sum of Distinct Subarrays With Length K / README_EN

发布于 2024-06-17 01:03:05 字数 5858 浏览 0 评论 0 收藏 0

2461. Maximum Sum of Distinct Subarrays With Length K

中文文档

Description

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

  • The length of the subarray is k, and
  • All the elements of the subarray are distinct.

Return _the maximum subarray sum of all the subarrays that meet the conditions__._ If no subarray meets the conditions, return 0.

_A subarray is a contiguous non-empty sequence of elements within an array._

 

Example 1:

Input: nums = [1,5,4,2,9,9,9], k = 3
Output: 15
Explanation: The subarrays of nums with length 3 are:
- [1,5,4] which meets the requirements and has a sum of 10.
- [5,4,2] which meets the requirements and has a sum of 11.
- [4,2,9] which meets the requirements and has a sum of 15.
- [2,9,9] which does not meet the requirements because the element 9 is repeated.
- [9,9,9] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions

Example 2:

Input: nums = [4,4,4], k = 3
Output: 0
Explanation: The subarrays of nums with length 3 are:
- [4,4,4] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • 1 <= nums[i] <= 105

Solutions

Solution 1: Sliding Window + Hash Table

We maintain a sliding window of length $k$, use a hash table $cnt$ to record the count of each number in the window, and use a variable $s$ to record the sum of all numbers in the window. Each time we slide the window, if all numbers in the window are unique, we update the answer.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.

class Solution:
  def maximumSubarraySum(self, nums: List[int], k: int) -> int:
    cnt = Counter(nums[:k])
    s = sum(nums[:k])
    ans = s if len(cnt) == k else 0
    for i in range(k, len(nums)):
      cnt[nums[i]] += 1
      s += nums[i]
      cnt[nums[i - k]] -= 1
      s -= nums[i - k]
      if cnt[nums[i - k]] == 0:
        del cnt[nums[i - k]]
      if len(cnt) == k:
        ans = max(ans, s)
    return ans
class Solution {
  public long maximumSubarraySum(int[] nums, int k) {
    int n = nums.length;
    Map<Integer, Integer> cnt = new HashMap<>(k);
    long s = 0;
    for (int i = 0; i < k; ++i) {
      cnt.merge(nums[i], 1, Integer::sum);
      s += nums[i];
    }
    long ans = cnt.size() == k ? s : 0;
    for (int i = k; i < n; ++i) {
      cnt.merge(nums[i], 1, Integer::sum);
      s += nums[i];
      if (cnt.merge(nums[i - k], -1, Integer::sum) == 0) {
        cnt.remove(nums[i - k]);
      }
      s -= nums[i - k];
      if (cnt.size() == k) {
        ans = Math.max(ans, s);
      }
    }
    return ans;
  }
}
class Solution {
public:
  long long maximumSubarraySum(vector<int>& nums, int k) {
    using ll = long long;
    int n = nums.size();
    unordered_map<int, ll> cnt;
    ll s = 0;
    for (int i = 0; i < k; ++i) {
      cnt[nums[i]]++;
      s += nums[i];
    }
    ll ans = cnt.size() == k ? s : 0;
    for (int i = k; i < n; ++i) {
      cnt[nums[i]]++;
      s += nums[i];
      cnt[nums[i - k]]--;
      s -= nums[i - k];
      if (cnt[nums[i - k]] == 0) {
        cnt.erase(nums[i - k]);
      }
      if (cnt.size() == k) {
        ans = max(ans, s);
      }
    }
    return ans;
  }
};
func maximumSubarraySum(nums []int, k int) (ans int64) {
  n := len(nums)
  cnt := map[int]int64{}
  var s int64
  for _, x := range nums[:k] {
    cnt[x]++
    s += int64(x)
  }
  if len(cnt) == k {
    ans = s
  }
  for i := k; i < n; i++ {
    cnt[nums[i]]++
    s += int64(nums[i])
    cnt[nums[i-k]]--
    s -= int64(nums[i-k])
    if cnt[nums[i-k]] == 0 {
      delete(cnt, nums[i-k])
    }
    if len(cnt) == k && ans < s {
      ans = s
    }
  }
  return
}
function maximumSubarraySum(nums: number[], k: number): number {
  const n = nums.length;
  const cnt: Map<number, number> = new Map();
  let s = 0;
  for (let i = 0; i < k; ++i) {
    cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1);
    s += nums[i];
  }
  let ans = cnt.size === k ? s : 0;
  for (let i = k; i < n; ++i) {
    cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1);
    s += nums[i];
    cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1);
    s -= nums[i - k];
    if (cnt.get(nums[i - k]) === 0) {
      cnt.delete(nums[i - k]);
    }
    if (cnt.size === k) {
      ans = Math.max(ans, s);
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文