|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 1176. Diet Plan Performance |
| 5 | + * |
| 6 | + * A dieter consumes calories[i] calories on the i-th day. |
| 7 | + * Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] |
| 8 | + * for all 0 <= i <= n-k), they look at T, the total calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]): |
| 9 | + * If T < lower, they performed poorly on their diet and lose 1 point; |
| 10 | + * If T > upper, they performed well on their diet and gain 1 point; |
| 11 | + * Otherwise, they performed normally and there is no change in points. |
| 12 | + * Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days. |
| 13 | + * |
| 14 | + * Note that the total points can be negative. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3 |
| 18 | + * Output: 0 |
| 19 | + * Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper. |
| 20 | + * calories[0] and calories[1] are less than lower so 2 points are lost. |
| 21 | + * calories[3] and calories[4] are greater than upper so 2 points are gained. |
| 22 | + * |
| 23 | + * Example 2: |
| 24 | + * Input: calories = [3,2], k = 2, lower = 0, upper = 1 |
| 25 | + * Output: 1 |
| 26 | + * Explanation: Since k = 2, we consider subarrays of length 2. |
| 27 | + * calories[0] + calories[1] > upper so 1 point is gained. |
| 28 | + * |
| 29 | + * Example 3: |
| 30 | + * Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5 |
| 31 | + * Output: 0 |
| 32 | + * Explanation: |
| 33 | + * calories[0] + calories[1] > upper so 1 point is gained. |
| 34 | + * lower <= calories[1] + calories[2] <= upper so no change in points. |
| 35 | + * calories[2] + calories[3] < lower so 1 point is lost. |
| 36 | + * |
| 37 | + * Constraints: |
| 38 | + * 1 <= k <= calories.length <= 10^5 |
| 39 | + * 0 <= calories[i] <= 20000 |
| 40 | + * 0 <= lower <= upper |
| 41 | + * */ |
| 42 | +public class _1176 { |
| 43 | + public static class Solution1 { |
| 44 | + public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { |
| 45 | + int sum = 0; |
| 46 | + int points = 0; |
| 47 | + for (int i = 0, j = 0; i <= calories.length - k && j < calories.length; j++) { |
| 48 | + sum += calories[j]; |
| 49 | + if (j - i > k - 1) { |
| 50 | + sum -= calories[i++]; |
| 51 | + } |
| 52 | + if (j - i == k - 1) { |
| 53 | + if (sum > upper) { |
| 54 | + points++; |
| 55 | + } else if (sum < lower) { |
| 56 | + points--; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return points; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments