1. Brute Force

class Solution:
    def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
        res = 0
        for i in range(len(calories) - k + 1):
            total = 0
            for j in range(i, i + k):
                total += calories[j]
            if total < lower:
                res -= 1
            elif total > upper:
                res += 1
        return res

Time & Space Complexity

  • Time complexity: O(n∗k)O(n * k)
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the array caloriescalories and kk is the window size.


2. Prefix Sum

class Solution:
    def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
        n = len(calories)
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i + 1] = prefix[i] + calories[i]

        res = 0
        for i in range(k, n + 1):
            total = prefix[i] - prefix[i - k]
            if total < lower:
                res -= 1
            elif total > upper:
                res += 1
        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Where nn is the length of the array caloriescalories.


3. Sliding Window

class Solution:
    def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
        res = total = 0
        for i in range(len(calories)):
            total += calories[i]
            if i >= k:
                total -= calories[i - k]
            if i >= k - 1:
                if total < lower:
                    res -= 1
                elif total > upper:
                    res += 1
        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the array caloriescalories.