Skip to content

2107. Number of Unique Flavors After Sharing K Candies 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  int shareCandies(vector<int>& candies, int k) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int candy : candies)
      ++count[candy];

    int unique = count.size();

    for (int i = 0; i < candies.size(); ++i) {
      if (--count[candies[i]] == 0) {
        count.erase(candies[i]);
        --unique;
      }
      if (i >= k && ++count[candies[i - k]] == 1)
        ++unique;
      if (i >= k - 1)
        ans = max(ans, unique);
    }

    return ans;
  }
};
 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
class Solution {
  public int shareCandies(int[] candies, int k) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int candy : candies)
      count.merge(candy, 1, Integer::sum);

    int unique = count.size();

    for (int i = 0; i < candies.length; ++i) {
      if (count.merge(candies[i], -1, Integer::sum) == 0) {
        count.remove(candies[i]);
        --unique;
      }
      if (i >= k) {
        count.merge(candies[i - k], 1, Integer::sum);
        if (count.get(candies[i - k]) == 1)
          ++unique;
      }
      if (i >= k - 1)
        ans = Math.max(ans, unique);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def shareCandies(self, candies: list[int], k: int) -> int:
    ans = 0
    count = collections.Counter(candies)
    unique = len(count)

    for i, candy in enumerate(candies):
      count[candy] -= 1
      if count[candy] == 0:
        del count[candy]
        unique -= 1
      if i >= k:
        count[candies[i - k]] += 1
        if count[candies[i - k]] == 1:
          unique += 1
      if i >= k - 1:
        ans = max(ans, unique)

    return ans