Problem Description
Given an array of integers representing the number of hours worked each day, a day is considered "tiring" if the hours exceed 8. A "well-performing interval" is a contiguous subarray where the number of tiring days is strictly greater than the number of non‐tiring days. The task is to return the length of the longest well-performing interval.
Key Insights
- Convert each day's hours into a score: +1 for a tiring day (hours > 8) and -1 otherwise.
- The problem becomes finding the longest subarray with a positive sum.
- Use a prefix sum array to compute cumulative scores.
- Use a monotonic (decreasing) stack to store candidate indices from the prefix sum array to enable efficient lookups.
- If the current prefix sum is positive, the interval from the beginning is valid.
- Otherwise, search in the stack for the leftmost index with prefix sum less than the current prefix sum to calculate the length of a valid interval.
Space and Time Complexity
Time Complexity: O(n) - Each element is processed in a constant number of operations. Space Complexity: O(n) - For the prefix sum array and the monotonic stack.
Solution
The approach works by first transforming the input array into a score array where each day contributes either +1 or -1 based on whether it is tiring or not. A prefix sum is then computed over these scores. A positive prefix sum indicates that the interval from the start is well-performing.
For cases where the prefix sum is not positive, we use a monotonic (decreasing) stack to keep track of indices that potentially represent the smallest prefix sums seen so far. As we iterate over the array, for the current prefix sum, we look for the earliest index in the stack that has a prefix sum less than the current, which indicates that the subarray between that index and the current index has a positive sum. We update the maximum interval length accordingly.
The solution uses a single traversal to build the prefix sum and another (reverse) traversal combined with the stack lookup to determine the maximum valid interval, ensuring an O(n) solution.