Number of Unique Flavors After Sharing K Candies Problem
Description
LeetCode Problem 2107.
You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the i^th 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:
0 <= candies.length <= 10^51 <= candies[i] <= 10^50 <= k <= candies.length
Solution
Approach: Sliding window + hash table
The k candies you give away form a window of length k; everything outside the window is yours. Keep a hash table cnt of the flavors outside the window with their counts, so the number of flavors you keep is the size of cnt.
Start with the window at the front, so cnt holds candies[k..n-1] and ans = cnt.size. Then slide the window right one step at a time: the candy candies[i-k] leaves the window and returns to you (increment its count), and candies[i] enters the window (decrement its count, delete it at zero). After each step update ans = max(ans, cnt.size).
Complexity: O(n) time, O(n) space.
class Solution:
def shareCandies(self, candies: List[int], k: int) -> int:
cnt = Counter(candies[k:])
ans = len(cnt)
for i in range(k, len(candies)):
cnt[candies[i - k]] += 1
cnt[candies[i]] -= 1
if cnt[candies[i]] == 0:
cnt.pop(candies[i])
ans = max(ans, len(cnt))
return ans