Longest Well-Performing Interval: Prefix Sum + Monotonic Decreasing Stack
A well-performing interval is a contiguous subarray where tiring days strictly outnumber non-tiring days. Map each element x to:
$$w(x) = \begin{cases} +1 & \text{if } x > 8 \text{ (tiring day)} \ -1 & \text{if } x \le 8 \text{ (non-tiring day)} \end{cases}$$
Now the problem becomes finding the maximum length subarray [l + 1, r] whose mapped sum is strictly positive:
$$\text{prefix}[r] - \text{prefix}[l] > 0 \iff \text{prefix}[l] < \text{prefix}[r]$$
Instead of checking all pairs (l, r) in $O(n^2)$ time, build a prefix array of length n + 1 (prefix[0] = 0) and use a monotonic decreasing stack of indices storing strictly smaller prefix values—achieving $O(n)$ time and $O(n)$ space.
Why a Monotonic Decreasing Stack Solves It in $O(n)$ Time
-
Building Candidate Start Indices (
stack):- Iterate
ifrom0ton. Pushiontostackonly ifstackis empty orprefix[i] < prefix[stack[-1]]. - Why? Suppose
a < bandprefix[a] <= prefix[b]. For any future indexr > b, ifprefix[b] < prefix[r], then automaticallyprefix[a] <= prefix[b] < prefix[r], andr - a > r - b. Thusbcan never beataas a left boundary. So the stack holds strictly decreasing prefix values at increasing indices.
- Iterate
-
Scanning Right Endpoints (
rfromndown to0):- Move
rbackward fromndown to0. - While
stackis non-empty andprefix[stack[-1]] < prefix[r]:- Pop
l = stack.pop(), updatebest = max(best, r - l), and continue popping smaller/earlier valid starts on the stack.
- Pop
- Why pop
lonce matched? Because asrmoves further left (r'decreases), any futurer' < rgives a smaller spanr' - l < r - lthan whatlalready achieved withr. Solwill never produce a longer interval later.
- Move
Quick Trace: hours = [9, 9, 6, 0, 6, 6, 9]
- Mapped weights:
[+1, +1, -1, -1, -1, -1, +1] prefix(0..7):[0, 1, 2, 1, 0, -1, -2, -1]- Stack push (
i = 0..7): pushes indices with strictly decreasingprefix:0(0),5(-1),6(-2) $\implies$stack = [0, 5, 6].
- Scan
r = 7down to0:- At
r = 7(prefix[7] = -1):stack.top()is6(-2 < -1) $\implies$ pop6,best = max(0, 7 - 6) = 1; next top is5(-1 < -1is false). - At
r = 2(prefix[2] = 2):stack.top()is5(-1 < 2) $\implies$ pop5,best = 7 - 5 = 2? Wait—earlierr = 7popped6(best = 1), and atr = 2,prefix[2] = 2 > prefix[5] = -1pops5(2 - 5is negative), while atr = 1(prefix[1] = 1 > -2? No, top is0withprefix[0] = 0 < 1$\implies$ pop0,best = max(1, 1 - 0) = 1). Total longest well-performing interval length in[9, 9, 6, 0, 6, 6, 9]is3(subarray[9, 9, 6]has two9s and one6, sum+1 + 1 - 1 = +1 > 0).
- At
Code Implementation
Python Solution
def longest_wpi(hours: list[int]) -> int:
n = len(hours)
prefix = [0] * (n + 1)
for i, h in enumerate(hours):
weight = 1 if h > 8 else -1
prefix[i + 1] = prefix[i] + weight
# Monotonic decreasing stack of indices with strictly smaller prefix values
stack: list[int] = []
for i in range(n + 1):
if not stack or prefix[i] < prefix[stack[-1]]:
stack.append(i)
best = 0
for r in range(n, -1, -1):
while stack and prefix[stack[-1]] < prefix[r]:
left_idx = stack.pop()
best = max(best, r - left_idx)
return best
C++ Solution
#include <vector>
#include <algorithm>
int longestWPI(const std::vector<int>& hours) {
int n = static_cast<int>(hours.size());
std::vector<int> prefix(n + 1, 0);
for (int i = 0; i < n; ++i) {
int weight = (hours[i] > 8) ? 1 : -1;
prefix[i + 1] = prefix[i] + weight;
}
std::vector<int> st;
st.reserve(n + 1);
for (int i = 0; i <= n; ++i) {
if (st.empty() || prefix[i] < prefix[st.back()]) {
st.push_back(i);
}
}
int best = 0;
for (int r = n; r >= 0; --r) {
while (!st.empty() && prefix[st.back()] < prefix[r]) {
int left_idx = st.back();
st.pop_back();
best = std::max(best, r - left_idx);
}
}
return best;
}
Complexity
- Time Complexity: $O(n)$ — each index is pushed onto and popped from the stack at most once across both loops.
- Auxiliary Space: $O(n)$ — stores
prefixof lengthn + 1and the stack of at mostn + 1indices.