有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果, 这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。 也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0 且 days[i] == 0 表示。 你打算每天 最多 吃一个苹果来保证营养均衡。注意,你可以在这 n 天之后继续吃苹果。 给你两个长度为 n 的整数数组 days 和 apples ,返回你可以吃掉的苹果的最大数目。 示例 1: 输入:apples = [1,2,3,5,2], days = [3,2,1,4,2] 输出:7 解释:你可以吃掉 7 个苹果:
第一天,你吃掉第一天长出来的苹果。
第二天,你吃掉一个第二天长出来的苹果。
第三天,你吃掉一个第二天长出来的苹果。过了这一天,第三天长出来的苹果就已经腐烂了。
第四天到第七天,你吃的都是第四天长出来的苹果。示例 2: 输入:apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] 输出:5 解释:你可以吃掉 5 个苹果:
第一天到第三天,你吃的都是第一天长出来的苹果。
第四天和第五天不吃苹果。
第六天和第七天,你吃的都是第六天长出来的苹果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 var eatenApples = function (apples, days ) { let appleBuck = []; let totalDays = apples.length let i = 0 ; let canEatAppleDays = 0 ; while (i === 0 || appleBuck.length !== 0 || totalDays >= 0 ) { if (i < apples.length ) { let appleNum = apples[i]; while (appleNum !== 0 ) { appleBuck.push (days[i]); appleNum-- } } appleBuck = appleBuck.sort ((a, b ) => a - b); appleBuck = appleBuck.filter (e => e != 0 ); let canEatApple = false ; if (appleBuck.length > 0 ) { canEatApple = true canEatAppleDays++ appleBuck.shift (); } appleBuck = appleBuck.map (e => e - 1 ) totalDays-- i++ }; return canEatAppleDays }; var eatenApples2 = function (apples, days ) { let appleBuck = []; let totalDays = apples.length let i = 0 ; let canEatAppleNum = 0 ; while (i === 0 || appleBuck.length !== 0 || totalDays >= 0 ) { let newDayAppleNum; let newDayAppleLeftDay; let todayHasApple = false ; if (i < apples.length ) { todayHasApple = apples[i] !== 0 ; newDayAppleNum = apples[i]; newDayAppleLeftDay = days[i]; } if (todayHasApple) { let last0Index; let lastLessIndex; let newappleBuck = appleBuck; if (appleBuck.length === 0 && i < apples.length ) { appleBuck = Array (newDayAppleNum).fill (newDayAppleLeftDay) } else { for (let j = 0 ; j < appleBuck.length ; j++) { const leftDay = appleBuck[j]; if (last0Index === 0 ) { appleBuck.slice (j, 1 ); } if (leftDay <= newDayAppleNum) { lastLessIndex = j; } } if (lastLessIndex) { newappleBuck = appleBuck.slice (0 , lastLessIndex).concat (Array (newDayAppleNum).fill (newDayAppleLeftDay)).concat (appleBuck.slice (lastLessIndex, appleBuck.length )) } appleBuck = newappleBuck; } } let canEatApple = false ; if (appleBuck.length > 0 ) { canEatApple = true canEatAppleNum++ appleBuck.shift (); } appleBuck = appleBuck.map (e => e - 1 ) totalDays-- i++ }; console .log ('canEatAppleNum' , canEatAppleNum); return canEatAppleNum }; eatenApples2 ([1 , 2 , 3 , 5 , 2 ], [3 , 2 , 1 , 4 , 2 ])