Longest Well-Performing Interval

medium prefix sum hash map

Problem

Given an array of work hours, a day is tiring if hours > 8. Find the length of the longest interval where tiring days strictly outnumber non-tiring days.

Inputhours = [9, 9, 6, 0, 6, 6, 9]
Output3
Map >8 → +1, else → -1; find longest subarray with sum > 0.

def longest_wpi(hours):
    first = {}
    s = 0
    best = 0
    for i, h in enumerate(hours):
        s += 1 if h > 8 else -1
        if s > 0:
            best = i + 1
        else:
            if (s - 1) in first:
                best = max(best, i - first[s - 1])
            first.setdefault(s, i)
    return best
function longestWPI(hours) {
  const first = new Map();
  let s = 0, best = 0;
  for (let i = 0; i < hours.length; i++) {
    s += hours[i] > 8 ? 1 : -1;
    if (s > 0) best = i + 1;
    else {
      if (first.has(s - 1)) best = Math.max(best, i - first.get(s - 1));
      if (!first.has(s)) first.set(s, i);
    }
  }
  return best;
}
class Solution {
    public int longestWPI(int[] hours) {
        Map<Integer, Integer> first = new HashMap<>();
        int s = 0, best = 0;
        for (int i = 0; i < hours.length; i++) {
            s += hours[i] > 8 ? 1 : -1;
            if (s > 0) best = i + 1;
            else {
                if (first.containsKey(s - 1)) best = Math.max(best, i - first.get(s - 1));
                first.putIfAbsent(s, i);
            }
        }
        return best;
    }
}
int longestWPI(vector<int>& hours) {
    unordered_map<int, int> first;
    int s = 0, best = 0;
    for (int i = 0; i < (int)hours.size(); i++) {
        s += hours[i] > 8 ? 1 : -1;
        if (s > 0) best = i + 1;
        else {
            if (first.count(s - 1)) best = max(best, i - first[s - 1]);
            if (!first.count(s)) first[s] = i;
        }
    }
    return best;
}
Time: O(n) Space: O(n)