Diet Plan Performance — LeetCode 1176 Python Solution
- Problem
- #1176
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The 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 (calories[i] + calories[i+1] + ...
Example
- 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.
Python solution
class Solution:
def dietPlanPerformance(
self, calories: List[int], k: int, lower: int, upper: int
) -> int:
s = list(accumulate(calories, initial=0))
ans, n = 0, len(calories)
for i in range(n - k + 1):
t = s[i + k] - s[i]
if t < lower:
ans -= 1
elif t > upper:
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1176. Diet Plan Performance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1176. Diet Plan Performance?
- LeetCode 1176. Diet Plan Performance is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1176. Diet Plan Performance?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1176. Diet Plan Performance?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1176. Diet Plan Performance cover?
- LeetCode 1176. Diet Plan Performance is tagged Array and Sliding Window on LeetCode.
- Is LeetCode 1176. Diet Plan Performance a premium problem?
- Yes. LeetCode 1176. Diet Plan Performance is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.