---
# System prepended metadata

title: 1124. Longest Well-Performing Interval
tags: [Leetcode, HashMap, Medium]

---

# 1124. Longest Well-Performing Interval
###### tags: `Leetcode` `Medium` `HashMap`
Link: https://leetcode.com/problems/longest-well-performing-interval/description/
## 思路
思路参考[这里](https://leetcode.com/problems/longest-well-performing-interval/solutions/334565/java-c-python-o-n-solution-life-needs-996-and-669/)
我们用score记录从index 0到目前index tiring day-nontiring day的差
那么如果目前score>0 那么i+1一定是目前最长的well-performing interval
如果score<0 那么我们应该找所有累积的score小于当前score的天数里面最前面的一个
所以我们在存进map的时候 对于每一个score都只存第一次出现时的index
仔细思考会发现我们并不需要把所有小于当前score的score都遍历一遍 我们只要看score-1在不在就可以了 因为score是负的 那么score-1 一定比score-2, score-3, ... 更早出现
## Code
```java=
class Solution {
    public int longestWPI(int[] hours) {
        int score = 0;
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;
        for(int i=0; i<hours.length; i++){
            score += hours[i]>8 ? 1: -1;
            if(score > 0) res = i+1;
            else if(map.containsKey(score-1)){
                res = Math.max(res, i-map.get(score-1));
            }
            map.putIfAbsent(score, i);
        }
        return res;
    }
}
```