#1744
Medium Algorithms Can you eat your favorite candy on your favorite day
Array Prefix Sum
36.0% acceptance
Mar 1, 2026
150
341
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have.
You also have a 0-indexed 2D integer array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].
You play a game with the following rules:
You start eating candies on day 0.
You cannot eat any candy of type i unless you have eaten all candies of type i - 1.
You must eat at least one candy per day until you finish eating all the candies.
Construct a boolean array answer such that answer[i] is true if you can eat a candy of type queries[i][favoriteTypei] on day queries[i][favoriteDayi] while not eating more than queries[i][dailyCapi] candies on any given day, and false otherwise.
Note that you can eat different types of candy on the same day, provided that you follow rule 2.
Return the constructed array answer.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn can_eat(candies_count: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<bool> {
let n = candies_count.len();
let mut prefix = vec![0i64; n + 1];
for i in 0..n {
prefix[i + 1] = prefix[i] + candies_count[i] as i64;
}
queries.iter().map(|q| {
let t = q[0] as usize;
let day = q[1] as i64;
let cap = q[2] as i64;
// Lower bound: eating max each day must reach type t by favoriteDay.
let can_reach = (day + 1) * cap >= prefix[t] + 1;
// Upper bound: eating min (1/day) must not exhaust type t before favoriteDay.
let not_passed = day + 1 <= prefix[t + 1];
can_reach && not_passed
}).collect()
}
}