Skip to content

Commit 919925a

Browse files
committed
feat(#1176): solve the problem #1176.Diet Plan Performance
1 parent 0fbc29a commit 919925a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

1176.Diet Plan Performance/README.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
A dieter consumes calories[i] calories on the i-th day. 
2+
3+
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] + ... + calories[i+k-1]):
4+
5+
- If T < lower, they performed poorly on their diet and lose 1 point; 
6+
- If T > upper, they performed well on their diet and gain 1 point;
7+
- Otherwise, they performed normally and there is no change in points.
8+
Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days.
9+
10+
Note that the total points can be negative.
11+
12+
 
13+
14+
**Example 1:**
15+
16+
```
17+
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
18+
Output: 0
19+
Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
20+
calories[0] and calories[1] are less than lower so 2 points are lost.
21+
calories[3] and calories[4] are greater than upper so 2 points are gained.
22+
```
23+
24+
**Example 2:**
25+
26+
```
27+
Input: calories = [3,2], k = 2, lower = 0, upper = 1
28+
Output: 1
29+
Explanation: Since k = 2, we consider subarrays of length 2.
30+
calories[0] + calories[1] > upper so 1 point is gained.
31+
```
32+
33+
**Example 3:**
34+
35+
```
36+
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
37+
Output: 0
38+
Explanation:
39+
calories[0] + calories[1] > upper so 1 point is gained.
40+
lower <= calories[1] + calories[2] <= upper so no change in points.
41+
calories[2] + calories[3] < lower so 1 point is lost.
42+
```
43+
44+
**Constraints:**
45+
46+
- 1 <= k <= calories.length <= 10^5
47+
- 0 <= calories[i] <= 20000
48+
- 0 <= lower <= upper
49+
50+
**Solution:**
51+
52+
```golang
53+
func dietPlanPerformance(calories []int, k int, lower int, upper int) int {
54+
left, sum, score, cLen := 0, 0, 0, len(calories)
55+
for right := 0; right < cLen; right++ {
56+
sum += calories[right]
57+
if (right - left + 1) == k {
58+
if sum > upper {
59+
score++
60+
} else if sum < lower {
61+
score--
62+
}
63+
sum -= calories[left]
64+
left++
65+
}
66+
}
67+
68+
return score
69+
}
70+
```

0 commit comments

Comments
 (0)