[LeetCode] 1124. Longest Well-Performing Interval
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:
Input: hours = [9,9,6,0,6,6,9] Output: 3 Explanation: The longest well-performing interval is [9,9,6].
Example 2:
Input: hours = [6,6,6] Output: 0
Constraints:
1 <= hours.length <= 104
0 <= hours[i] <= 16
表现良好的最长时间段。
给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
请你返回「表现良好时间段」的最大长度。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-well-performing-interval
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是前缀和。
我们需要遍历一遍 input 数组。遍历的时候,遇到大于 8 小时的天数就加一,反之则减一。为什么加一或者减一是因为我们只需要知道他是否大于 8 小时,我们并不在意他到底具体是几个小时。遍历的过程中我们记录一个前缀和。如果这个前缀和一直大于 0,说明从开头到目前的 i 位置,都是满足题意的子数组,这一段都是表现良好的时间段。但是如果在过程中前缀和开始小于 0 了,我们就需要看一下上一次前缀和小于 0 的位置在哪里,设这个位置为 j。那么 j - i 这一段就是目前表现良好的时间段。
注意代码里面,当前缀和小于 0 的时候,我们去 hashmap 里找的是 score - 1,那是因为我们只做了 +1 和 -1 操作,最先出现的负数一定是 -1,所以我们直接找上一次出现 -1 的位置即可。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int longestWPI(int[] hours) { 3 int res = 0; 4 int score = 0; 5 HashMap<Integer, Integer> map = new HashMap<>(); 6 for (int i = 0; i < hours.length; i++) { 7 int cur = hours[i]; 8 score += cur > 8 ? 1 : -1; 9 if (score > 0) { 10 res = i + 1; 11 } else { 12 map.putIfAbsent(score, i); 13 if (map.containsKey(score)) { 14 res = Math.max(res, i - map.get(score)); 15 } 16 } 17 } 18 return res; 19 } 20 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
2022-02-15 [LeetCode] 1779. Find Nearest Point That Has the Same X or Y Coordinate
2021-02-15 [LeetCode] 1636. Sort Array by Increasing Frequency
2020-02-15 [LeetCode] 289. Game of Life