-
Notifications
You must be signed in to change notification settings - Fork 0
/
1248. Count Number of Nice Subarrays
85 lines (55 loc) · 1.34 KB
/
1248. Count Number of Nice Subarrays
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Solution {
public int numberOfSubarrays(int[] nums, int k)
{
int n = nums.length;
int[] count = new int[n + 1];
count[0] = 1;
int result = 0, t = 0;
for (int v : nums)
{
t += v & 1;
if(t - k >= 0)
{
result += count[t - k];
}
count[t]++;
}
return result;
}
/*
RUNTIME 14 MS, MEMORY 54.84 MB
public int numberOfSubarrays(int[] nums, int k)
{
return numberOfSubarraysAtMost(nums, k) - numberOfSubarraysAtMost(nums, k - 1);
}
public int numberOfSubarraysAtMost(int[] nums, int k)
{
int result = 0;
for(int l = 0, r = 0; r <= nums.length;)
{
if(k >= 0)
{
result += r - l;
if(r == nums.length)
{
break;
}
if(nums[r] % 2 == 1)
{
k--;
}
r++;
}
else
{
if (nums[l] % 2 == 1)
{
k++;
}
l++;
}
}
return result;
}
*/
}