# 1176. Diet Plan Performance

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MiGI9ERv9oZbE0VzSkb%2F-MiGQ0oBxHQQzKcw0uVD%2Fimage.png?alt=media\&token=b66211da-a3c3-4f57-b7fc-76158d793f39)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MiGI9ERv9oZbE0VzSkb%2F-MiGQ3KFS_oEnPyg1m1O%2Fimage.png?alt=media\&token=535e619e-0b7f-4e94-bd34-83120d47a4e3)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MiGI9ERv9oZbE0VzSkb%2F-MiGQ5t7TjNf9C4JpwNJ%2Fimage.png?alt=media\&token=013ffe75-ee01-423b-b91c-1af5ccad1fc4)

## 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;
    }
}
```
