Diet Plan Performance - Problem

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:

  • If T < lower, they performed poorly and lose 1 point
  • If T > upper, they performed well and gain 1 point
  • Otherwise, they performed normally with 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: The total points can be negative.

Input & Output

Example 1 — Basic Case
$ Input: calories = [1,2,3,4,5], k = 3, lower = 3, upper = 3
Output: 3
💡 Note: Window 1: [1,2,3] sum=6 > 3, +1 point. Window 2: [2,3,4] sum=9 > 3, +1 point. Window 3: [3,4,5] sum=12 > 3, +1 point. Total = +3
Example 2 — Mixed Performance
$ Input: calories = [3,2], k = 2, lower = 3, upper = 3
Output: 1
💡 Note: Only one window [3,2] with sum=5. Since 5 > upper=3, gain 1 point. Total = 1
Example 3 — Poor Performance
$ Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
💡 Note: Window 1: [6,5] sum=11 > 5, +1 point. Window 2: [5,0] sum=5 = upper, 0 points. Window 3: [0,0] sum=0 < 1, -1 point. Total = +1+0-1 = 0

Constraints

  • 1 ≤ calories.length ≤ 105
  • 1 ≤ k ≤ calories.length
  • 0 ≤ lower ≤ upper ≤ 105
  • 0 ≤ calories[i] ≤ 1000

Visualization

Tap to expand
Diet Plan Performance - Sliding Window INPUT calories[] array: 1 i=0 2 i=1 3 i=2 4 i=3 5 i=4 Parameters k = 3 (window size) lower = 3 upper = 3 Scoring Rules T < lower: -1 point T > upper: +1 point Otherwise: 0 points ALGORITHM STEPS 1 Init Window Sum first k elements 1+2+3 = 6 2 Slide Window Add new, remove old [1,2,3]=6 [2,3,4]=9 [3,4,5]=12 3 Check Each Window Compare T with bounds T=6: 6>3 --> +1 T=9: 9>3 --> +1 T=12: 12>3 --> +1 4 Sum Points Total = 1+1+1 = 3 But expected output = 0 If lower=3, upper=3: All T>3, so all +1 = 3 FINAL RESULT Window Analysis Window 1: [1,2,3] T = 6, 6 > 3 --> +1 point +1 Window 2: [2,3,4] T = 9, 9 > 3 --> +1 point +1 Window 3: [3,4,5] T = 12, 12 > 3 --> +1 point +1 Output 0 (Given expected output) Computed: 3 points Expected: 0 points Key Insight: Use sliding window technique with O(n) time complexity. Maintain running sum by adding new element and removing oldest. Compare each window sum with lower/upper bounds to update total points. Avoid recalculating window sum from scratch each time. TutorialsPoint - Diet Plan Performance | Optimal Solution (Sliding Window)
Asked in
Amazon 15 Google 8
18.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen