[LeetCode] Diet Plan Performance

1176. Diet Plan Performance

A dieter consumes calories[i] calories on the i-th day.

Given an integer k``k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k``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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int dietPlanPerformance(vector<int>& A, int k, int lower, int upper) {
long long sum = accumulate(begin(A), begin(A) + k, 0ll), res = 0;
for(int i = k; i < A.size(); i++) {
if(sum < lower) res--;
if(sum > upper) res++;
sum = sum + A[i] - A[i-k];
}
if(sum < lower) res--;
if(sum > upper) res++;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/14/PS/LeetCode/diet-plan-performance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.