Codepath

Daily App Usage Peaks

Unit 4 Session 1 Advanced (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the structure of the input?

    • A: The input is a list of 24 integers, where each integer represents the number of minutes spent on apps during a specific hour (from hour 0 to hour 23).
  • Q: What is the output?

    • A: The output is a tuple containing the start hour (integer) and the total screen time (integer) for the three-hour period with the highest total usage.
  • Q: What should the function return if multiple periods have the same total?

    • A: The function should return the earliest period.
  • Q: Are there any constraints on the input, such as non-negative integers?

    • A: It is assumed that the list contains non-negative integers.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list of screen times, summing the values for each set of three consecutive hours. Track the maximum sum and the corresponding start hour.

1) Initialize two variables: `max_sum` to 0 and `start_hour` to 0.
2) Iterate over the list from index 0 to 21 (as each three-hour period needs three values):
   a) Calculate the sum of the current hour and the next two hours.
   b) If this sum is greater than `max_sum`, update `max_sum` to this value and `start_hour` to the current index.
3) Return `start_hour` and `max_sum` as a tuple.

**⚠️ Common Mistakes**

- Forgetting to stop the loop early enough to avoid index errors.
- Not properly updating the `max_sum` and `start_hour` when a new maximum is found.

I-mplement

def peak_usage_hours(screen_time):
    max_sum = 0
    start_hour = 0

    for i in range(len(screen_time) - 2):
        current_sum = screen_time[i] + screen_time[i + 1] + screen_time[i + 2]
        if current_sum > max_sum:
            max_sum = current_sum
            start_hour = i

    return start_hour, max_sum
Fork me on GitHub