2461. Maximum Sum of Distinct Subarrays With Length K
- Hardness: \(\color{orange}\textsf{Medium}\)
- Ralated Topics:
Array
、Hash Table
、Sliding Window
- \(\color{blue}\textsf{Weekly Contest 318}\)
一、題目
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.
Example 3:
- Input:
- Output:
Constraints:
1 <= k <= nums.length <= 10^5
1 <= nums[i] <= 10^5
二、分析
- 標準的
Sliding Window
題型,將window
控制在固定大小k
,並檢查window
中沒有重複的數字。
三、解題
1. Sliding Window
- Time complexity: \(O(n)\)
- Space complexity: \(O(n)\)
long long maximumSubarraySum(vector<int>& nums, int k) {
unordered_map<int,int> map;
int valid = 0;
long long res = 0;
long long sum = 0;
int left = 0, right = 0;
while (right < nums.size()) {
int x = nums[right++]; // 右指針移動
sum += x; // 將值加入和
map[x]++; // 記錄右指針移動時數字的個數
if (map[x] == 1) valid++; // 右指針移動時,數字個數為 1 時,有效數加 1
if (right - left == k) { // 將 window 控制在大小為 k
if (valid == k) res = max(res, sum); // 滿足條件,比較大小
int y = nums[left++]; // 左指針移動
if (map[y] == 1) valid--; // 左指針移動時,數字個數為 1 時,有效數減 1
map[y]--; // 記錄左指針移動時數字的個數
sum -= y; // 將值移去和
}
}
return res;
}