Diet Plan Performance
Score a length-k window by total calories vs lower/upper limits — fixed-size sliding window.
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 = 3→0calories = [3,2], k = 2, lower = 0, upper = 1→1
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#
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; }};func dietPlanPerformance(calories []int, k, lower, upper int) int { sum := 0 score := 0 for i := 0; i < len(calories); 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}from typing import List
class Solution: def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int: s = 0 score = 0 for i, c in enumerate(calories): s += c if i >= k: s -= calories[i - k] if i >= k - 1: if s > upper: score += 1 elif s < lower: score -= 1 return scorevar dietPlanPerformance = function(calories, k, lower, upper) { let sum = 0; let score = 0; for (let i = 0; i < calories.length; 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;};class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { long sum = 0; int score = 0; for (int i = 0; i < calories.length; 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; }}function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { let sum = 0; let score = 0; for (let i = 0; i < calories.length; 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#
Related#