Unit 4 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the structure of the input?
Q: What is the output?
Q: What should the function return if multiple periods have the same total?
Q: Are there any constraints on the input, such as non-negative integers?
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.
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