Diet Plan Performance

Score a length-k window by total calories vs lower/upper limits — fixed-size sliding window.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window array

Problem#

For every length-k window of calories, compare its sum T to thresholds lower and upper. Score +1 if T > upper, −1 if T < lower, else 0. Return the total score.

Examples#

  • calories = [1,2,3,4,5], k = 1, lower = 3, upper = 30
  • calories = [3,2], k = 2, lower = 0, upper = 11

Constraints#

  • 1 <= k <= calories.length <= 10^5.

Approach#

Rolling sum over a fixed window; for each completed window add ±1 based on threshold comparison.

Solution#

Diet Plan Performance
class Solution {
public:
int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
long long sum = 0;
int score = 0;
for (int i = 0; i < (int)calories.size(); ++i) {
sum += calories[i];
if (i >= k) sum -= calories[i - k];
if (i >= k - 1) {
if (sum > upper) ++score;
else if (sum < lower) --score;
}
}
return score;
}
};

Editorial#

The window is scored only once it’s “full” (i >= k - 1). Two threshold comparisons; ties (between lower and upper, inclusive bounds) contribute 0 — the strict inequalities match the problem’s “greater than” / “less than” phrasing.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.