LeetCode 3339: Find the Number of K-Even Arrays

Dynamic Programming

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:

  1. Initialize a variable count to store the total count of subarrays with exactly k even numbers.
  2. Iterate through all subarrays of the given array.
  3. For each subarray, count the number of even numbers.
  4. If the count of even numbers equals k, increment the count variable.
  5. 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...