Powered By GitBook
1176.Diet Plan Performance

1176. Diet Plan Performance

难度:Easy
A dieter consumes calories[i] calories on the i-th day. For every consecutive sequence of k days, they look at T, the total calories consumed during that sequence of k days:
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. Return the total number of points the dieter has after all calories.length days.
Note that: The total points could be negative.
1
Example 1:
2
3
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
4
Output: 0
5
Explaination: calories[0], calories[1] < lower and calories[3], calories[4] > upper, total points = 0.
6
Example 2:
7
8
Input: calories = [3,2], k = 2, lower = 0, upper = 1
9
Output: 1
10
Explaination: calories[0] + calories[1] > upper, total points = 1.
11
Example 3:
12
13
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
14
Output: 0
15
Explaination: calories[0] + calories[1] > upper, lower <= calories[1] + calories[2] <= upper, calories[2] + calories[3] < lower, total points = 0.
16
17
18
Constraints:
19
20
1 <= k <= calories.length <= 10^5
21
0 <= calories[i] <= 20000
22
0 <= lower <= upper
Copied!
连续k天的和的范围决定加分还是扣分,直接遍历一遍即可。
1
class Solution {
2
public:
3
int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
4
int startSum=0;
5
int points=0;
6
for( int i=0;i<k;i++)
7
startSum += calories[i];
8
if(startSum>upper)
9
++points;
10
else if(startSum < lower)
11
--points;
12
for(int i=k; i<calories.size();i++)
13
{
14
startSum = startSum - calories[i-k]+calories[i];
15
if(startSum>upper)
16
++points;
17
else if(startSum < lower)
18
--points;
19
20
}
21
return points;
22
}
23
};
Copied!
执行用时 :44 ms, 在所有 C++ 提交中击败了40.28%的用户 内存消耗 :13.1 MB, 在所有 C++ 提交中击败了100.00%的用户
Last modified 2yr ago
Copy link