Skip to main content
Back to problems
#1176
Easy Algorithms

Diet plan performance

Array Sliding Window
55.9% acceptance
Mar 31, 2026
174
297
A dieter consumes calories[i] calories on the i-th day. Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] 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]): If T < lower, they performed poorly on their diet and lose 1 point; If T > upper, they performed well on their diet and gain 1 point; Otherwise, they performed normally and there is no change in points. Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days. Note that the total points can be negative.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn diet_plan_performance(calories: Vec<i32>, k: i32, lower: i32, upper: i32) -> i32 {
    let k = k as usize;
    let mut sum: i32 = calories[..k].iter().sum();
    let mut points = 0;
    if sum < lower { points -= 1; }
    else if sum > upper { points += 1; }
    for i in k..calories.len() {
      sum += calories[i] - calories[i - k];
      if sum < lower { points -= 1; }
      else if sum > upper { points += 1; }
    }
    points
  }
}