Skip to content

Commit f9cd13d

Browse files
authored
Create longest-well-performing-interval.cpp
1 parent d1a58a4 commit f9cd13d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int longestWPI(vector<int>& hours) {
7+
int result = 0, accu = 0;
8+
unordered_map<int, int> lookup;
9+
for (int i = 0; i < hours.size(); ++i) {
10+
accu += (hours[i] > 8) ? 1 : -1;
11+
if (accu > 0) {
12+
result = i + 1;
13+
} else if (lookup.count(accu - 1)) {
14+
// lookup[accu-1] is the leftmost idx with smaller accu,
15+
// because from 1 to some positive k,
16+
// lookup[accu-i] is a strickly increasing sequence
17+
result = max(result, i - lookup[accu - 1]);
18+
}
19+
if (!lookup.count(accu)) {
20+
lookup[accu] = i;
21+
}
22+
}
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)