Problem solution · Java

Find the Number of K-Even Arrays

Find the Number of K-Even Arrays: a Java solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
30 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Find the Number of K-Even Arrays, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 30 lines of Java from the credited upstream file 3339.java.
  • The implementation visibly relies on sequence storage, cached states.
  • 2 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind the Number of K-Even Arrays · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int countOfArrays(int n, int m, int k) {    final int MOD = 1_000_000_007;    final int even = m / 2;   // the number of even numbers in [1, m]    final int odd = m - even; // the number of odd numbers in [1, m]    // dp[i][j][0/1] := the number of arrays of length i with j consecutive even    // number pairs ending in an even number (0) or an odd number (1)    int[][][] dp = new int[n + 1][k + 1][2];     // Base case: arrays of length 1    // For an array of length 1, we can't have any even number pairs yet.    dp[1][0][0] = even;    dp[1][0][1] = odd;     for (int i = 2; i <= n; ++i)      for (int j = 0; j <= k; ++j) {        // 1. Appending an even number to an array ending in an even number        //    creates a new consecutive even number pair.        // 2. Appending an even number to an array ending in an odd number.        dp[i][j][0] = (int) (((long) (j > 0 ? dp[i - 1][j - 1][0] : 0) * even +                              (long) dp[i - 1][j][1] * even) %                             MOD);        // 3. Appending an odd number to an array.        dp[i][j][1] = (int) ((long) (dp[i - 1][j][0] + dp[i - 1][j][1]) * odd % MOD);      }     return (dp[n][k][0] + dp[n][k][1]) % MOD;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗