1124. Longest Well-Performing Interval

1124. Longest Well-Performing Interval

Description

Difficulty: Medium

Related Topics: Array, Hash Table, Stack, Monotonic Stack, Prefix Sum

We are given hours, a list of the number of hours worked per day for a given employee.

A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.

A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.

Example 1:

1
2
3
Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].

Example 2:

1
2
Input: hours = [6,6,6]
Output: 0

Constraints:

  • 1 <= hours.length <= 104
  • 0 <= hours[i] <= 16

Hints/Notes

  • preSum + map

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    int longestWPI(vector<int>& hours) {
        int size = hours.size();
        vector<intpreSum(size + 10);
        for (int i = 0; i < size; i++) {
            preSum[i + 1] = preSum[i] + (hours[i] > 8 ? 1 : -1);
        }
        map<intint> m;
        int res = 0;
        for (int i = 0; i <= size; i++) {
            if (!m.contains(preSum[i])) {
                m[preSum[i]] = i;
            }
            if (preSum[i] > 0) {
                res = max(res, i);
            } else {
                if (m.contains(preSum[i] - 1)) {
                    res = max(res, i - m[preSum[i] - 1]);
                }
            }
        }
        return res;
    }
};