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;
}
}