https://algo.monster/problems/count_number_of_nice_subarrays
def count_nice_subarrays(k: int, arr: List[int]) → int:
left = 0
result = 0
final_array = []
while left < len(arr) - k + 1:
right = left
sub_array = []
num_odd = k
while num_odd and right < len(arr):
sub_array.append(arr[right])
if arr[right] % 2 != 0:
num_odd -= 1
right += 1
if num_odd == 0 and sub_array:
result += 1
final_array.append(sub_array)
left += 1
print(final_array)
return result
Can anyone please share how for the third case, there are 12 sub arrays containing 3 odd numbers…?
There should be only 4
[2, 4, 5, 7, 8, 10, 11], [4, 5, 7, 8, 10, 11], [5, 7, 8, 10, 11], [7, 8, 10, 11, 12, 14, 15]
Below are the subarray with odd for the 3rd use case
2 4 5 7 8 10 11
2 4 5 7 8 10 11 12
2 4 5 7 8 10 11 12 14
4 5 7 8 10 11
4 5 7 8 10 11 12
4 5 7 8 10 11 12 14
5 7 8 10 11
5 7 8 10 11 12
5 7 8 10 11 12 14
7 8 10 11 12 14 15
7 8 10 11 12 14 15 18
7 8 10 11 12 14 15 18 20
Below are the combinations for use case 3
2 4 5 7 8 10 11
2 4 5 7 8 10 11 12
2 4 5 7 8 10 11 12 14
4 5 7 8 10 11
4 5 7 8 10 11 12
4 5 7 8 10 11 12 14
5 7 8 10 11
5 7 8 10 11 12
5 7 8 10 11 12 14
7 8 10 11 12 14 15
7 8 10 11 12 14 15 18
7 8 10 11 12 14 15 18 20
[2, 4, 5, 7, 8, 10, 11], [2, 4, 5, 7, 8, 10, 11, 12], [2, 4, 5, 7, 8, 10, 11, 12, 14], [4, 5, 7, 8, 10, 11], [4, 5, 7, 8, 10, 11, 12], [4, 5, 7, 8, 10, 11, 12, 14], [5, 7, 8, 10, 11], [5, 7, 8, 10, 11, 12], [5, 7, 8, 10, 11, 12, 14], [7, 8, 10, 11, 12, 14, 15], [7, 8, 10, 11, 12, 14, 15, 18], [7, 8, 10, 11, 12, 14, 15, 18, 20].
My javascript solution is too slow for the last case. And the solution provided is too mathematically difficult for me to understand, even the graphics didn’t help. I think author should work on the solutions to make it more intuitive to understand given the price of premium is not cheap…
function countNiceSubarrays(k, arr) {
let a = 0
let b = a + k
let ans = 0
function checkOdd(array, k) {
let count = k
for(let i = 0; i<array.length; i++){
if(array[i]%2 !== 0){
count--
}
}
if(count == 0){
return true
} else {
return false
}
}
while(a < arr.length - k + 1){
let subArray = arr.slice(a, b)
let isNice = checkOdd(subArray, k)
//if b < arr.length && odd number < k
if(b<arr.length && !isNice){
b++
}
//if b == arr.length && odd number < k
else if( b == arr.length && !isNice){
++a
b = a + k
if(a == 0 && b == arr.length && !isNice){
return ans
}
}
//if b < arr.length && add number == k
else if(b<arr.length && isNice){
b++
ans++
}
//if b == arr.length && add number == k
else if(b == arr.length && isNice){
++a
b = a + k
ans++
}
}
return ans;
}