Problem solution · C++

Find the Number of K-Even Arrays

Find the Number of K-Even Arrays: a C++ 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
34 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

  • 34 lines of C++ from the credited upstream file 3339-2.cpp.
  • 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 · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int countOfArrays(int n, int m, int k) {    constexpr int kMod = 1'000'000'007;    const int even = m / 2;    // the number of even numbers in [1, m]    const int odd = m - even;  // the number of odd numbers in [1, m]    // dp[j][0/1] := the number of arrays of length so far i with j consecutive    // even number pairs ending in an even number (0) or an odd number (1)    vector<vector<int>> dp(k + 1, vector<int>(2));     // Base case: arrays of length 1    // For an array of length 1, we can't have any even number pairs yet.    dp[0][0] = even;    dp[0][1] = odd;     for (int i = 2; i <= n; ++i) {      vector<vector<int>> newDp(k + 1, vector<int>(2));      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.        newDp[j][0] = (static_cast<long>(j > 0 ? dp[j - 1][0] : 0) * even +                       static_cast<long>(dp[j][1]) * even) %                      kMod;        // 3. Appending an odd number to an array.        newDp[j][1] = static_cast<long>(dp[j][0] + dp[j][1]) * odd % kMod;      }      dp = std::move(newDp);    }     return (dp[k][0] + dp[k][1]) % kMod;  }}; 

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 ↗