|
| 1 | +/** |
| 2 | + * 1176. Diet Plan Performance |
| 3 | + * https://leetcode.com/problems/diet-plan-performance/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * A dieter consumes calories[i] calories on the i-th day. |
| 7 | + * |
| 8 | + * Given an integer k, for every consecutive sequence of k days |
| 9 | + * (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), |
| 10 | + * they look at T, the total calories consumed during that sequence of k days |
| 11 | + * (calories[i] + calories[i+1] + ... + calories[i+k-1]): |
| 12 | + * - If T < lower, they performed poorly on their diet and lose 1 point; |
| 13 | + * - If T > upper, they performed well on their diet and gain 1 point; |
| 14 | + * - Otherwise, they performed normally and there is no change in points. |
| 15 | + * |
| 16 | + * Initially, the dieter has zero points. Return the total number of points the dieter |
| 17 | + * has after dieting for calories.length days. |
| 18 | + * |
| 19 | + * Note that the total points can be negative. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} calories |
| 24 | + * @param {number} k |
| 25 | + * @param {number} lower |
| 26 | + * @param {number} upper |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var dietPlanPerformance = function(calories, k, lower, upper) { |
| 30 | + let windowSum = 0; |
| 31 | + let points = 0; |
| 32 | + |
| 33 | + for (let i = 0; i < k; i++) { |
| 34 | + windowSum += calories[i]; |
| 35 | + } |
| 36 | + |
| 37 | + if (windowSum < lower) points--; |
| 38 | + else if (windowSum > upper) points++; |
| 39 | + |
| 40 | + for (let i = k; i < calories.length; i++) { |
| 41 | + windowSum = windowSum - calories[i - k] + calories[i]; |
| 42 | + |
| 43 | + if (windowSum < lower) points--; |
| 44 | + else if (windowSum > upper) points++; |
| 45 | + } |
| 46 | + |
| 47 | + return points; |
| 48 | +}; |
0 commit comments