#2107
Medium Algorithms Number of unique flavors after sharing k candies
Array Hash Table Sliding Window
60.5% acceptance
Mar 31, 2026
118
7
No description available.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn share_candies(candies: Vec<i32>, k: i32) -> i32 {
let k = k as usize;
let n = candies.len();
if k == 0 {
let unique: HashSet<i32> = candies.iter().cloned().collect();
return unique.len() as i32;
}
// Count total frequency
let mut total: HashMap<i32, usize> = HashMap::new();
for &c in &candies {
*total.entry(c).or_insert(0) += 1;
}
// Initial window: first k elements given away
let mut window: HashMap<i32, usize> = HashMap::new();
for i in 0..k {
*window.entry(candies[i]).or_insert(0) += 1;
}
// Count unique flavors kept (those with total[c] - window[c] > 0)
let mut unique = 0i32;
for (&c, &t) in &total {
let w = window.get(&c).copied().unwrap_or(0);
if t > w {
unique += 1;
}
}
let mut ans = unique;
// Slide window
for i in k..n {
let out = candies[i - k];
let entering = candies[i];
// Remove out from window
let w_out = window.get(&out).copied().unwrap_or(0);
let t_out = *total.get(&out).unwrap();
if t_out - w_out == 0 {
// was not kept, now will be kept
unique += 1;
}
*window.entry(out).or_insert(0) -= 1;
// Add entering to window
let w_in = window.get(&entering).copied().unwrap_or(0);
let t_in = *total.get(&entering).unwrap();
if t_in - w_in == 1 {
// was kept with count 1, now won't be kept
unique -= 1;
}
*window.entry(entering).or_insert(0) += 1;
ans = ans.max(unique);
}
ans
}
}