File: diet-plan-performance/solution.py

Date: 2026-06-06

Time: 16:23

diet-plan-performance/solution.py

Purpose

This file solves LeetCode 1176 — Diet Plan Performance. It evaluates a dieter's performance by sliding a fixed-size window across daily calorie data, scoring +1 for days where the window sum exceeds an upper threshold and -1 where it falls below a lower threshold.

Key Components

Solution.dietPlanPerformance(calories, k, lower, upper) -> int

The single method on the class. Contract:

Patterns

Sliding window (fixed-size). The solution computes sum(calories[:k]) once, then maintains the window sum incrementally by adding the entering element and subtracting the leaving element. This is the textbook O(n) approach — it avoids recomputing the sum from scratch for each of the n−k+1 windows.

The first window is handled outside the loop (lines 14–18), and subsequent windows are processed inside the for loop (lines 20–25). The scoring logic (if < lower: -1, elif > upper: +1, else: 0) is duplicated between the two blocks rather than extracted into a helper — a common trade-off in competitive/LeetCode code favoring directness over DRY.

Dependencies

Imports: typing.List — used only for the type annotation on calories.

Imported by: diet-plan-performance/test_solution.py — the test file exercises this solution. The large "Imported By" list in the prompt is an artifact of the repo's shared test infrastructure, not direct imports of this specific module.

Flow

1. Initialize points = 0 and compute the sum of the first k elements.

2. Score the first window against lower/upper.

3. Iterate i from k to len(calories) - 1:

4. Return accumulated points.

The total number of scoring evaluations is exactly len(calories) - k + 1 (one per valid window position).

Invariants

Error Handling

None. The method trusts the caller to provide valid inputs per the LeetCode contract. No bounds checking, no type validation, no exception handling.