Skip to content

1176. Diet Plan Performance 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
    int ans = 0;
    int sum = 0;

    for (int i = 0; i < calories.size(); ++i) {
      sum += calories[i];
      if (i < k - 1)
        continue;
      if (i >= k)
        sum -= calories[i - k];
      if (sum < lower)
        --ans;
      else if (sum > upper)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
    int ans = 0;
    int sum = 0;

    for (int i = 0; i < calories.length; ++i) {
      sum += calories[i];
      if (i < k - 1)
        continue;
      if (i >= k)
        sum -= calories[i - k];
      if (sum < lower)
        --ans;
      else if (sum > upper)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def dietPlanPerformance(
      self,
      calories: list[int],
      k: int,
      lower: int,
      upper: int,
  ) -> int:
    ans = 0
    summ = 0

    for i, calorie in enumerate(calories):
      summ += calorie
      if i < k - 1:
        continue
      if i >= k:
        summ -= calories[i - k]
      if summ < lower:
        ans -= 1
      elif summ > upper:
        ans += 1

    return ans