We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Diet Plan Performance

Number: 1280

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Given an array of daily calorie intakes and an integer k, calculate the total "points" by inspecting every contiguous subarray of length k. For each subarray, compute the total calories T:

  • If T is less than a given lower threshold, the dieter loses a point.
  • If T is greater than a given upper threshold, the dieter gains a point.
  • Otherwise, no points are added or subtracted. Return the overall points after considering all contiguous subarrays of length k.

Key Insights

  • Use the sliding window technique to efficiently compute the sum for each subarray of length k.
  • Instead of recomputing the sum from scratch for each window, update the previous window's sum by subtracting the element leaving and adding the new element entering.
  • Directly compare the current sum with the thresholds to update the points.

Space and Time Complexity

Time Complexity: O(n), as we iterate through the array once. Space Complexity: O(1), using only a few extra variables for maintaining the sum and point count.


Solution

We use a sliding window approach:

  1. Compute the initial sum for the first k days.
  2. Check whether this sum falls below the lower threshold, above the upper threshold, or in between, and update the points accordingly.
  3. Slide the window by one day: subtract the calorie count of the day leaving the window and add the calorie count of the new day entering the window.
  4. For each new window, perform the same comparison to update the points.
  5. Return the total points at the end.

Data structures used are simple numeric variables. This method leverages the sliding window to avoid redundant summation work, ensuring efficiency even with a large input size.


Code Solutions

# Python implementation with comments
def dietPlanPerformance(calories, k, lower, upper):
    # Initialize total points to zero
    points = 0
    # Calculate the sum of the first window of k days
    window_sum = sum(calories[:k])
    
    # Check and update points for the initial window
    if window_sum < lower:
        points -= 1
    elif window_sum > upper:
        points += 1
    
    # Slide through the rest of the array, one day at a time
    for i in range(k, len(calories)):
        # Remove the calorie from the day exiting the window and add the current day's calorie
        window_sum += calories[i] - calories[i - k]
        # Update points based on the current window sum
        if window_sum < lower:
            points -= 1
        elif window_sum > upper:
            points += 1
            
    return points

# Example usage:
print(dietPlanPerformance([1,2,3,4,5], 1, 3, 3))
← Back to All Questions