-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2841-maximum-sum-of-almost-unique-subarray.js
More file actions
51 lines (44 loc) · 1.24 KB
/
2841-maximum-sum-of-almost-unique-subarray.js
File metadata and controls
51 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 2841. Maximum Sum of Almost Unique Subarray
* https://leetcode.com/problems/maximum-sum-of-almost-unique-subarray/
* Difficulty: Medium
*
* You are given an integer array nums and two positive integers m and k.
*
* Return the maximum sum out of all almost unique subarrays of length k of nums. If no such
* subarray exists, return 0.
*
* A subarray of nums is almost unique if it contains at least m distinct elements.
*
* A subarray is a contiguous non-empty sequence of elements within an array.
*/
/**
* @param {number[]} nums
* @param {number} m
* @param {number} k
* @return {number}
*/
var maxSum = function(nums, m, k) {
const map = new Map();
let subarraySum = 0;
let result = 0;
for (let i = 0; i < k; i++) {
map.set(nums[i], (map.get(nums[i]) || 0) + 1);
subarraySum += nums[i];
}
if (map.size >= m) {
result = subarraySum;
}
for (let i = k; i < nums.length; i++) {
map.set(nums[i - k], map.get(nums[i - k]) - 1);
if (map.get(nums[i - k]) === 0) {
map.delete(nums[i - k]);
}
map.set(nums[i], (map.get(nums[i]) || 0) + 1);
subarraySum = subarraySum - nums[i - k] + nums[i];
if (map.size >= m) {
result = Math.max(result, subarraySum);
}
}
return result;
};