Leetcode 1124. Longest Well-Performing Interval

4 篇文章 0 订阅
3 篇文章 0 订阅

Leetcode 1124. Longest Well-Performing Interval

We starts with a score = 0,
If the working hour > 8, we plus 1 point.
Otherwise we minus 1 point.
We want find the maximum interval that have strict positive score.

After one day of work, if we find the total score > 0,
the whole interval has positive score,
so we set res = i + 1.

If the score is a new lowest score, we record the day by seen[cur] = i.
seen[score] means the first time we see the score is seen[score]th day.

We want a positive score, so we want to know the first occurrence of score - 1.
score - x also works, but it comes later than score - 1.
So the maximum interval is i - seen[score - 1]

如果cur_sum = -2, index =j, 我们需要找到cur_sum=-3第一次出现的位置i, (j-i) 就是一个interval.
如果cur_sum >0 index =i,当前区间内(0,i)都是intreval.
如果cur_sum =0, 当前区间the number of tiring days is equal to the number of non-tiring days.
不需要保证区间的子区间也满足 the number of tiring days is strictly larger than the number of non-tiring days.

class Solution {
    public int longestWPI(int[] hours) {
        int res = 0, score = 0, n = hours.length;
        Map<Integer, Integer> seen = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            score += hours[i] > 8 ? 1 : -1;
            if (score > 0) {
                res = i + 1;
            } else {
                seen.putIfAbsent(score, i);
                if (seen.containsKey(score - 1)){
                    res = Math.max(res, i - seen.get(score - 1));
                    System.out.println(score +", "+i +" - "+seen.get(score - 1));
                }
                    
                // for (Map.Entry mapElement : seen.entrySet()) { 
                //     int key = (int)mapElement.getKey(); 
                //     int value = (int)mapElement.getValue(); 
                //     System.out.println(key + " : " + value); 
                // } 
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值