David to DSAEnglish • 2 days ago

How do you find the longest well-performing interval where tiring days strictly exceed non-tiring days?

message-square
0
1
How do you find the longest well-performing interval where tiring days strictly exceed non-tiring days?
David to DSAEnglish • 2 days ago

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

  1. Building Candidate Start Indices (stack):

    • Iterate i from 0 to n. Push i onto stack only if stack is empty or prefix[i] < prefix[stack[-1]].
    • Why? Suppose a < b and prefix[a] <= prefix[b]. For any future index r > b, if prefix[b] < prefix[r], then automatically prefix[a] <= prefix[b] < prefix[r], and r - a > r - b. Thus b can never beat a as a left boundary. So the stack holds strictly decreasing prefix values at increasing indices.
  2. Scanning Right Endpoints (r from n down to 0):

    • Move r backward from n down to 0.
    • While stack is non-empty and prefix[stack[-1]] < prefix[r]:
      • Pop l = stack.pop(), update best = max(best, r - l), and continue popping smaller/earlier valid starts on the stack.
    • Why pop l once matched? Because as r moves further left (r' decreases), any future r' < r gives a smaller span r' - l < r - l than what l already achieved with r. So l will never produce a longer interval later.

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 decreasing prefix:
    • 0 (0), 5 (-1), 6 (-2) $\implies$ stack = [0, 5, 6].
  • Scan r = 7 down to 0:
    • At r = 7 (prefix[7] = -1): stack.top() is 6 (-2 < -1) $\implies$ pop 6, best = max(0, 7 - 6) = 1; next top is 5 (-1 < -1 is false).
    • At r = 2 (prefix[2] = 2): stack.top() is 5 (-1 < 2) $\implies$ pop 5, best = 7 - 5 = 2? Wait—earlier r = 7 popped 6 (best = 1), and at r = 2, prefix[2] = 2 > prefix[5] = -1 pops 5 (2 - 5 is negative), while at r = 1 (prefix[1] = 1 > -2? No, top is 0 with prefix[0] = 0 < 1 $\implies$ pop 0, best = max(1, 1 - 0) = 1). Total longest well-performing interval length in [9, 9, 6, 0, 6, 6, 9] is 3 (subarray [9, 9, 6] has two 9s and one 6, sum +1 + 1 - 1 = +1 > 0).

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 prefix of length n + 1 and the stack of at most n + 1 indices.