Diet Plan Performance

easy sliding window prefix sum array

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.

Inputcalories = [1, 2, 3, 4, 5], k = 1, lower = 3, upper = 3
Output0
Windows [1] and [2] are below 3 (−1 each), [4] and [5] are above 3 (+1 each), [3] is in range. Total = −1 −1 +1 +1 = 0.

def 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;
}
Time: O(n) Space: O(1)