|
| 1 | +/** |
| 2 | + * 1744. Can You Eat Your Favorite Candy on Your Favorite Day? |
| 3 | + * https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] |
| 7 | + * represents the number of candies of the ith type you have. You are also given a 2D array |
| 8 | + * queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. |
| 9 | + * |
| 10 | + * You play a game with the following rules: |
| 11 | + * - You start eating candies on day 0. |
| 12 | + * - You cannot eat any candy of type i unless you have eaten all candies of type i - 1. |
| 13 | + * - You must eat at least one candy per day until you have eaten all the candies. |
| 14 | + * |
| 15 | + * Construct a boolean array answer such that answer.length == queries.length and answer[i] is |
| 16 | + * true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more |
| 17 | + * than dailyCapi candies on any day, and false otherwise. Note that you can eat different |
| 18 | + * types of candy on the same day, provided that you follow rule 2. |
| 19 | + * |
| 20 | + * Return the constructed array answer. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[]} candiesCount |
| 25 | + * @param {number[][]} queries |
| 26 | + * @return {boolean[]} |
| 27 | + */ |
| 28 | +var canEat = function(candiesCount, queries) { |
| 29 | + const prefixSums = [0]; |
| 30 | + for (const count of candiesCount) { |
| 31 | + prefixSums.push(prefixSums.at(-1) + count); |
| 32 | + } |
| 33 | + |
| 34 | + const result = new Array(queries.length); |
| 35 | + for (let i = 0; i < queries.length; i++) { |
| 36 | + const [type, day, cap] = queries[i]; |
| 37 | + const minCandies = day; |
| 38 | + const maxCandies = (day + 1) * cap; |
| 39 | + const typeStart = prefixSums[type]; |
| 40 | + const typeEnd = prefixSums[type + 1] - 1; |
| 41 | + result[i] = maxCandies > typeStart && minCandies <= typeEnd; |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | +}; |
0 commit comments