Problem Description
Given an array candiesCount where candiesCount[i] represents the number of candies of type i, and a list of queries where each query is of the form [favoriteType, favoriteDay, dailyCap]. You must determine for each query if it’s possible to eat a candy of type favoriteType exactly on favoriteDay under these rules:
- You start eating candies on day 0.
- You cannot eat any candy of type i unless you have finished all candies of type i - 1.
- You must eat at least one candy per day until all candies are finished. Also, you are restricted by not eating more than dailyCap candies on any day. Return a boolean array indicating if it's possible to have a candy of favoriteType eaten on favoriteDay.
Key Insights
- Use a prefix sum array over candiesCount to quickly determine the total candies consumed before a given candy type.
- For each query, determine the minimum and maximum candies that can be eaten by favoriteDay given the daily eating restrictions.
- Check if the range of possible candies consumed overlaps with the range in which the favoriteType candies are eaten.
- The valid conditions are:
- The minimum candies eaten (day+1, since you eat at least one per day) should be no more than the total candies up to favoriteType.
- The maximum candies eaten ( (day+1) * dailyCap ) must be greater than the total candies before favoriteType.
Space and Time Complexity
Time Complexity: O(n + q) where n is the length of candiesCount and q is the number of queries. Space Complexity: O(n) for storing the prefix sum array (ignoring the output array).
Solution
First, build a prefix sum array from candiesCount to compute cumulative totals. For each query, define:
- minCandiesEaten = favoriteDay + 1 (if you eat one candy every day)
- maxCandiesEaten = (favoriteDay + 1) * dailyCap (if you eat the maximum allowed candies every day)
- prevCandies = (if favoriteType is 0 then 0 else prefix[favoriteType - 1])
- currentTotal = prefix[favoriteType] (total candies up to and including the favorite type)
The query is satisfied if and only if:
- minCandiesEaten <= currentTotal
- maxCandiesEaten > prevCandies
These conditions ensure that there is an intersection between the range of possible total candies eaten by the favorite day and the set of candies that contains favoriteType.