We can convert the problem into finding the longest subarray with a positive sum by mapping tiring days to +1 and non-tiring days to -1. Using prefix sums and a hash map to record the first occurrence of each prefix sum, we can efficiently find the longest interval.
classSolution {
public:int longestWPI(vector<int>& hours) {
int n = hours.size(), ans =0, s =0;
unordered_map<int, int> first;
for (int i =0; i < n; ++i) {
s += hours[i] >8?1:-1;
if (s >0) ans = i +1;
else {
if (first.count(s -1)) ans = max(ans, i - first[s -1]);
}
if (!first.count(s)) first[s] = i;
}
return ans;
}
};
funclongestWPI(hours []int) int {
n, ans, s:= len(hours), 0, 0first:=map[int]int{}
fori:=0; i < n; i++ {
ifhours[i] > 8 {
s++ } else {
s-- }
ifs > 0 {
ans = i+1 } elseifv, ok:=first[s-1]; ok {
ifi-v > ans {
ans = i-v }
}
if_, ok:=first[s]; !ok {
first[s] = i }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publicintlongestWPI(int[] hours) {
int n = hours.length, ans = 0, s = 0;
Map<Integer, Integer> first =new HashMap<>();
for (int i = 0; i < n; ++i) {
s += hours[i]> 8 ? 1 : -1;
if (s > 0) ans = i + 1;
elseif (first.containsKey(s - 1)) ans = Math.max(ans, i - first.get(s - 1));
if (!first.containsKey(s)) first.put(s, i);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funlongestWPI(hours: IntArray): Int {
var ans = 0var s = 0val first = mutableMapOf<Int, Int>()
for (i in hours.indices) {
s +=if (hours[i] > 8) 1else -1if (s > 0) ans = i + 1elseif (first.containsKey(s - 1)) ans = maxOf(ans, i - first[s - 1]!!)
if (!first.containsKey(s)) first[s] = i
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deflongestWPI(self, hours: list[int]) -> int:
ans = s =0 first = {}
for i, h in enumerate(hours):
s +=1if h >8else-1if s >0:
ans = i +1elif (s -1) in first:
ans = max(ans, i - first[s -1])
if s notin first:
first[s] = i
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnlongest_wpi(hours: Vec<i32>) -> i32 {
letmut ans =0;
letmut s =0;
letmut first = std::collections::HashMap::new();
for (i, &h) in hours.iter().enumerate() {
s +=if h >8 { 1 } else { -1 };
if s >0 {
ans = (i +1) asi32;
} elseiflet Some(&v) = first.get(&(s -1)) {
ans = ans.max((i - v) asi32);
}
first.entry(s).or_insert(i);
}
ans
}
}