|
| 1 | +/** |
| 2 | + * 1705. Maximum Number of Eaten Apples |
| 3 | + * https://leetcode.com/problems/maximum-number-of-eaten-apples/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a special kind of apple tree that grows apples every day for n days. On the ith day, |
| 7 | + * the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] |
| 8 | + * the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any |
| 9 | + * apples, which are denoted by apples[i] == 0 and days[i] == 0. |
| 10 | + * |
| 11 | + * You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep |
| 12 | + * eating after the first n days. |
| 13 | + * |
| 14 | + * Given two integer arrays days and apples of length n, return the maximum number of apples you |
| 15 | + * can eat. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} apples |
| 20 | + * @param {number[]} days |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var eatenApples = function(apples, days) { |
| 24 | + const expiryCounts = new Array(40001).fill(0); |
| 25 | + let result = 0; |
| 26 | + let earliestExpiry = Infinity; |
| 27 | + let maxExpiry = apples.length; |
| 28 | + |
| 29 | + for (let day = 0; day <= maxExpiry; day++) { |
| 30 | + if (earliestExpiry < day) earliestExpiry = day; |
| 31 | + |
| 32 | + if (day < apples.length && apples[day]) { |
| 33 | + const expiry = day + days[day] - 1; |
| 34 | + expiryCounts[expiry] += apples[day]; |
| 35 | + earliestExpiry = Math.min(expiry, earliestExpiry); |
| 36 | + maxExpiry = Math.max(expiry, maxExpiry); |
| 37 | + } |
| 38 | + |
| 39 | + while (!expiryCounts[earliestExpiry] && earliestExpiry < maxExpiry) { |
| 40 | + earliestExpiry++; |
| 41 | + } |
| 42 | + |
| 43 | + if (expiryCounts[earliestExpiry]) { |
| 44 | + result++; |
| 45 | + expiryCounts[earliestExpiry]--; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return result; |
| 50 | +}; |
0 commit comments