Magicsheet logo

Diet Plan Performance

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Diet Plan Performance

What is this problem about?

The Diet Plan Performance interview question asks you to evaluate a person's diet over a period of time. You are given an array of calories consumed each day, a window of days represented by an integer kk, and two thresholds: lower and upper. For every consecutive period of kk days, you calculate the total calories consumed. If the total is less than lower, the person loses 1 point. If the total is greater than upper, the person gains 1 point. Otherwise, the points remain unchanged. The goal is to find the total points accumulated by the end of the diet plan.

Why is this asked in interviews?

Amazon frequently uses this coding problem to test a candidate's understanding of basic data processing and optimization. It specifically targets the Sliding Window interview pattern. While a beginner might recalculate the sum for every window from scratch (O(n×k)O(n \times k)), an experienced engineer knows how to update the sum in constant time (O(1)O(1)) as the window slides. This demonstrates efficiency and attention to performance, which are critical traits for software engineers working on large-scale systems.

Algorithmic pattern used

The primary pattern is the Sliding Window. Instead of summing kk elements for every starting position, you maintain a running total. For the first kk days, you calculate the sum normally. For each subsequent day, you add the calories of the new day entering the window and subtract the calories of the day that just left. This ensures that each window's evaluation takes O(1)O(1) time after an initial O(k)O(k) setup, leading to an overall O(n)O(n) time complexity.

Example explanation

Suppose calories = [1, 2, 3, 4, 5], k = 2, lower = 3, upper = 6.

  1. Days 0 and 1: Total calories = 1+2=31 + 2 = 3. 33 is not <3< 3 and not >6> 6. Points = 0.
  2. Days 1 and 2: Total calories = 2+3=52 + 3 = 5. 55 is not <3< 3 and not >6> 6. Points = 0.
  3. Days 2 and 3: Total calories = 3+4=73 + 4 = 7. 7>67 > 6, so points = 1.
  4. Days 3 and 4: Total calories = 4+5=94 + 5 = 9. 9>69 > 6, so points = 2. Total points = 2.

Common mistakes candidates make

  • Inefficient Summing: Recalculating the sum for every window, which leads to O(n×k)O(n \times k) complexity and may time out.
  • Off-by-one Errors: Incorrectly handling the indices when adding the new day and removing the old day from the window.
  • Initialization: Forgetting to handle the first window correctly before starting the sliding loop.

Interview preparation tip

Master the Sliding Window interview pattern. It is a fundamental technique for problems involving contiguous subarrays or substrings. When you see "fixed-size window" or "consecutive elements," your first thought should be: "Can I update the result by just looking at the elements entering and leaving the window?"

Similar Questions