1124. 表现良好的最长时间段

188 阅读1分钟

给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。

我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。

所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。

请你返回「表现良好时间段」的最大长度。

    let count = 0; // 大于8h的累计天数
    let result = 0;
    let map = new Map();
    for (let i = 0; i < hours.length; i++) {
        if (hours[i] > 8) {
            count++;
        } else {
            count--;
        }
        if (count > 0) {
            result = i + 1;
        } else {
            if (!map.has(count)) {
                map.set(count, i); // 记录第一次count<=0的下标
            }
            if (map.has(count - 1)) { // 如果有count的前一次记录,此时count-1到count符合要求
                result = Math.max(result, i - map.get(count - 1));
            }
        }
    }
    return result;
};