> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/two-pointer/1176.-diet-plan-performance.md).

# 1176. Diet Plan Performance

![](/files/-MiGQ0oBxHQQzKcw0uVD)

![](/files/-MiGQ3KFS_oEnPyg1m1O)

![](/files/-MiGQ5t7TjNf9C4JpwNJ)

## sliding windows

time: O(n)

space: O(1)

first try like this:

```java
class Solution {
    public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
        int points = 0;
        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += calories[i];
        }
        if (sum < lower) points--;
        if (sum > upper) points++;
        for (int i = k; i < calories.length; i++) {
            sum += calories[i] - calories[i-k];
            if (sum < lower) points--;
            if (sum > upper) points++;
        }
        return points;
    }
}
```

one for loop

```java
class Solution {
    // 0 1 2
    public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
        int points = 0;
        int sum = 0;
        for (int i = 0; i < calories.length; i++) {
            sum += calories[i];
            
            if (i >= k) { // when have over k sum, have a new sliding window sum
                sum -= calories[i-k];
            }
            if (i >= k-1) { // when have k sum, start to calculate points
                if (sum < lower) points--;
                if (sum > upper) points++;
            }
        }
        return points;
    }
}
```
