-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 152.java
More file actions
34 lines (27 loc) · 852 Bytes
/
Day 152.java
File metadata and controls
34 lines (27 loc) · 852 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.HashMap;
class Solution {
public int longestSubarray(int[] arr, int k) {
int n = arr.length;
HashMap<Integer, Integer> map = new HashMap<>();
int prefixSum = 0;
int maxLen = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > k) {
prefixSum += 1;
} else {
prefixSum -= 1;
}
if (prefixSum > 0) {
maxLen = i + 1;
} else {
if (map.containsKey(prefixSum - 1)) {
maxLen = Math.max(maxLen, i - map.get(prefixSum - 1));
}
}
if (!map.containsKey(prefixSum)) {
map.put(prefixSum, i);
}
}
return maxLen;
}
}