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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/two-pointer/1176.-diet-plan-performance.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
