Diet Plan Performance Problem
Description
LeetCode Problem 1176.
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.
Example 1:
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
Output: 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.
Example 2:
Input: calories = [3,2], k = 2, lower = 0, upper = 1
Output: 1
Explanation: Since k = 2, we consider subarrays of length 2.
calories[0] + calories[1] > upper so 1 point is gained.
Example 3:
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost.
Constraints:
1 <= k <= calories.length <= 10^50 <= calories[i] <= 200000 <= lower <= upper
Solution
Approach: Sliding Window
Every window of k consecutive days is scored separately, so we only need the total T of each window. Recomputing each total from scratch costs O(n * k). Instead, slide the window one day to the right: add the day that comes in and subtract the day that drops out.
Walk through the days with a running total:
- Add
calories[i]. - Once
i >= k, the window is one day too long: subtractcalories[i - k]. - Once
i >= k - 1, the window holds exactlykdays: lose a point iftotal < lower, gain one iftotal > upper.
The comparisons are strict, so a total equal to lower or upper changes nothing. The largest total is 105 * 20000 = 2 * 109, which still fits in a 32-bit signed integer.
Complexity: O(n) time and O(1) extra space.
class Solution:
def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
points = 0
total = 0 # calories of the last k days
for i, c in enumerate(calories):
total += c
if i >= k:
total -= calories[i - k] # day i - k leaves the window
if i >= k - 1: # the window holds exactly k days
if total < lower:
points -= 1
elif total > upper:
points += 1
return points