[LeetCode] Number of Unique Flavors After Sharing K Candies

2107. Number of Unique Flavors After Sharing K Candies

You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the ith candy. Your mom wants you to share these candies with your little sister by giving her k consecutive candies, but you want to keep as many flavors of candies as possible.

Return the maximum number of unique flavors of candy you can keep after sharing with your sister.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int shareCandies(vector<int>& A, int k) {
unordered_map<int, int> freq;
for(auto& a : A) freq[a]++;
int res = 0, now = freq.size();
for(int i = 0; i < A.size(); i++) {
if(--freq[A[i]] == 0) now -= 1;
if(i >= k and ++freq[A[i-k]] == 1) now += 1;
if(i >= k - 1) res = max(res, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/06/PS/LeetCode/number-of-unique-flavors-after-sharing-k-candies/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.