LeetCode 3339: Find the Number of K-Even Arrays
Problem Description
Explanation:
To solve this problem, we can iterate through all possible subarrays of the given array and count the number of subarrays that have exactly k
even numbers. We can achieve this by keeping track of the count of even numbers in each subarray.
Algorithm:
- Initialize a variable
count
to store the total count of subarrays with exactlyk
even numbers. - Iterate through all subarrays of the given array.
- For each subarray, count the number of even numbers.
- If the count of even numbers equals
k
, increment thecount
variable. - Return the final
count
value.
Time Complexity: O(n^2) where n is the length of the given array. Space Complexity: O(1)
:
Solutions
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int evenCount = 0;
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 == 0) {
evenCount++;
}
if (evenCount == k) {
count++;
}
}
}
return count;
}
}
Loading editor...