Longest Well-Performing Interval - Problem
You are a workplace efficiency analyst tracking employee work hours over a period of days. Given an array hours representing the number of hours worked each day by an employee, you need to find the longest well-performing interval.
Here's what makes this interesting:
- A day is considered tiring if the employee works more than 8 hours (> 8)
- A day is considered non-tiring if the employee works 8 hours or less (β€ 8)
- A well-performing interval is any consecutive sequence of days where there are strictly more tiring days than non-tiring days
Your task is to return the length of the longest such interval.
Example: If hours = [9,9,6,0,6,6,9], the interval from index 0 to 2 has 2 tiring days and 1 non-tiring day, making it well-performing with length 3.
Input & Output
example_1.py β Standard Case
$
Input:
[9,9,6,0,6,6,9]
βΊ
Output:
3
π‘ Note:
The longest well-performing interval is [9,9,6] from index 0 to 2. It has 2 tiring days (9,9) and 1 non-tiring day (6), so tiring > non-tiring with length 3.
example_2.py β Single Element
$
Input:
[9]
βΊ
Output:
1
π‘ Note:
Single tiring day forms a well-performing interval of length 1 since 1 tiring day > 0 non-tiring days.
example_3.py β No Solution
$
Input:
[6,6,6]
βΊ
Output:
0
π‘ Note:
All days are non-tiring (β€8 hours). No interval can have more tiring days than non-tiring days, so the answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Energy Transformation
Convert work hours to energy: >8 hours = +1 energy, β€8 hours = -1 energy
2
Running Energy Score
Keep track of cumulative energy at each day
3
Find Best Streak
Use hash map to remember when you first hit each energy level
4
Calculate Maximum
Find the longest period with positive net energy
Key Takeaway
π― Key Insight: Transform the problem into finding the longest subarray with positive sum using the +1/-1 conversion, then leverage prefix sums with hash map lookups for O(n) efficiency.
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(1) hash map operations
β Linear Growth
Space Complexity
O(n)
Hash map can store at most n different prefix sum values
β‘ Linearithmic Space
Constraints
- 1 β€ hours.length β€ 104
- 0 β€ hours[i] β€ 16
- A tiring day is when hours[i] > 8
- Well-performing means tiring days > non-tiring days in the interval
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code