Diet Plan Performance
Problem
A dieter records daily calories in calories. For every consecutive sequence of k days, sum the calories T. If T < lower they lose 1 point; if T > upper they gain 1 point; otherwise the points stay the same. Return the total points.
calories = [1, 2, 3, 4, 5], k = 1, lower = 3, upper = 30def diet_plan_performance(calories, k, lower, upper):
window = sum(calories[:k])
points = 0
for i in range(k, len(calories) + 1):
if window < lower:
points -= 1
elif window > upper:
points += 1
if i < len(calories):
window += calories[i] - calories[i - k]
return points
function dietPlanPerformance(calories, k, lower, upper) {
let window = 0;
for (let i = 0; i < k; i++) window += calories[i];
let points = 0;
for (let i = k; i <= calories.length; i++) {
if (window < lower) points -= 1;
else if (window > upper) points += 1;
if (i < calories.length) window += calories[i] - calories[i - k];
}
return points;
}
class Solution {
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
int window = 0;
for (int i = 0; i < k; i++) window += calories[i];
int points = 0;
for (int i = k; i <= calories.length; i++) {
if (window < lower) points -= 1;
else if (window > upper) points += 1;
if (i < calories.length) window += calories[i] - calories[i - k];
}
return points;
}
}
int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
int window = 0;
for (int i = 0; i < k; i++) window += calories[i];
int points = 0;
for (int i = k; i <= (int)calories.size(); i++) {
if (window < lower) points -= 1;
else if (window > upper) points += 1;
if (i < (int)calories.size()) window += calories[i] - calories[i - k];
}
return points;
}
Explanation
We score every block of k consecutive days. For each block we add up the calories: below lower loses a point, above upper gains a point, and anything in between leaves the score unchanged. The smart part is computing each block's sum without re-adding from scratch.
We build the first window's sum once, then slide it: to move one day forward we add the new day on the right and subtract the day that fell off the left, using window += calories[i] - calories[i - k]. This keeps each step at constant cost.
At every window position we compare the running window sum to lower and upper and adjust points accordingly. This works because the sliding update always reflects exactly the current k-day total.
Example: calories = [1,2,3,4,5], k = 1, lower = upper = 3. Single-day windows: 1 and 2 are below (−1 each), 3 is in range, 4 and 5 are above (+1 each). The total is -1 -1 +1 +1 = 0.
Because the window slides instead of being rebuilt, the entire log is scored in one linear pass.