Diet Plan Performance

This problem asks for calculating a running score based on the total caloric intake over a window of k days. The initial score is 0 and then the score is adjusted based on the total calories within the window: If it’s lower than a given threshold, the score is decremented by 1; if it’s higher than another given threshold, the score is incremented by 1; otherwise, the score doesn’t change.

Here is a Python solution that uses a sliding window approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
        score = 0
        window_sum = sum(calories[:k])

        if window_sum < lower:
            score -= 1
        elif window_sum > upper:
            score += 1

        for i in range(k, len(calories)):
            window_sum += calories[i] - calories[i - k]
            if window_sum < lower:
                score -= 1
            elif window_sum > upper:
                score += 1

        return score

In this solution, we first calculate the sum of the first k elements to initialize our sliding window. Then, we adjust the score based on the total calories. After that, we iterate through the rest of the list, each time moving the window 1 step to the right by adding the new element and subtracting the old one, then adjusting the score again. The final score is returned after traversing all elements.

This solution has a time complexity of O(n), where n is the length of the calories list, since we go through the list once. The space complexity is O(1) because the extra space used doesn’t change with the size of the input.