-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_36.java
More file actions
59 lines (54 loc) · 1.5 KB
/
Copy pathDay_36.java
File metadata and controls
59 lines (54 loc) · 1.5 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Subarrays with K Different Integers
class Solution {
public int atmost(int[] nums, int k){
int n = nums.length;
int cnt = 0, l = 0;
Map<Integer,Integer> mpp = new HashMap<>();
for(int r=0;r<n;r++){
mpp.put(nums[r],mpp.getOrDefault(nums[r],0)+1);
while(mpp.size()>k){
int val = nums[l];
int freq = mpp.get(val) - 1;
if(freq == 0) mpp.remove(val);
else mpp.put(val,freq);
l++;
}
cnt+=(r-l+1);
}
return cnt;
}
public int subarraysWithKDistinct(int[] nums, int k) {
return atmost(nums,k) - atmost(nums,k-1);
}
}
// Count Subarrays With Score Less Than K
class Solution {
public long countSubarrays(int[] nums, long k) {
int n = nums.length, l = 0;
long cnt = 0, sum = 0;
for(int r=0;r<n;r++){
sum+=nums[r];
while(sum * (r-l+1) >= k){
sum-=nums[l];
l++;
}
cnt+=(r-l+1);
}
return cnt;
}
}
// Max Consecutive Ones III
class Solution {
public int longestOnes(int[] nums, int k) {
int n = nums.length, maxlen = 0, zeroes = 0,l=0;
for(int r=0;r<n;r++){
if(nums[r] == 0) zeroes++;
while(zeroes>k){
if(nums[l] == 0) zeroes--;
l++;
}
maxlen = Math.max(maxlen,r-l+1);
}
return maxlen;
}
}