Formatted question description: https://leetcode.ca/all/2107.html

2107. Number of Unique Flavors After Sharing K Candies (Medium)

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.

 

Example 1:

Input: candies = [1,2,2,3,4,3], k = 3
Output: 3
Explanation: 
Give the candies in the range [1, 3] (inclusive) with flavors [2,2,3].
You can eat candies with flavors [1,4,3].
There are 3 unique flavors, so return 3.

Example 2:

Input: candies = [2,2,2,2,3,3], k = 2
Output: 2
Explanation: 
Give the candies in the range [3, 4] (inclusive) with flavors [2,3].
You can eat candies with flavors [2,2,2,3].
There are 2 unique flavors, so return 2.
Note that you can also share the candies with flavors [2,2] and eat the candies with flavors [2,2,3,3].

Example 3:

Input: candies = [2,4,5], k = 0
Output: 3
Explanation: 
You do not have to give any candies.
You can eat the candies with flavors [2,4,5].
There are 3 unique flavors, so return 3.

 

Constraints:

  • 1 <= candies.length <= 105
  • 1 <= candies[i] <= 105
  • 0 <= k <= candies.length

Companies:
Microsoft

Related Topics:
Array, Hash Table, Sliding Window

Similar Questions:

Solution 1. Fixed-length Sliding Window

// OJ: https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies/
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int shareCandies(vector<int>& A, int k) {
        unordered_map<int, int> cnt;
        int ans = 0;
        for (int n : A) cnt[n]++;
        for (int i = 0, N = A.size(); i < N; ++i) { // Give out candies in window `[i-k+1, i]`
            cnt[A[i]]--; // Give out `A[i]`
            if (i - k >= 0) cnt[A[i - k]]++; // Reclaim `A[i-k]`
            if (cnt[A[i]] == 0) cnt.erase(A[i]);
            if (i >= k - 1) ans = max(ans, (int)cnt.size()); // Take the maximum possible unique flavors left after giving out.
        }
        return ans;
    }
};

Discuss

https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies/discuss/1658450/C%2B%2B-Fixed-length-Sliding-Window

All Problems

All Solutions