Problem solution · C++

Build Array Where You Can Find The Maximum Exactly K Comparisons

Build Array Where You Can Find The Maximum Exactly K Comparisons: 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 Build Array Where You Can Find The Maximum Exactly K Comparisons, 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 1420.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 6 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 codeBuild Array Where You Can Find The Maximum Exactly K Comparisons · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int numOfArrays(int n, int m, int k) {    constexpr int kMod = 1'000'000'007;    // dp[i][j][k] := the number of ways to build an array of length i, where j    // is the maximum number and k is `search_cost`    vector<vector<vector<int>>> dp(        n + 1, vector<vector<int>>(m + 1, vector<int>(k + 1)));     for (int j = 1; j <= m; ++j)      dp[1][j][1] = 1;     for (int i = 2; i <= n; ++i)                 // for each length      for (int j = 1; j <= m; ++j)               // for each max value        for (int cost = 1; cost <= k; ++cost) {  // for each cost          // 1. Appending any of [1, j] in the i-th position doesn't change the          //    maximum and cost.          dp[i][j][cost] = static_cast<long>(j) * dp[i - 1][j][cost] % kMod;          // 2. Appending j in the i-th position makes j the new max and cost 1.          for (int prevMax = 1; prevMax < j; ++prevMax) {            dp[i][j][cost] += dp[i - 1][prevMax][cost - 1];            dp[i][j][cost] %= kMod;          }        }     int ans = 0;    for (int j = 1; j <= m; ++j) {      ans += dp[n][j][k];      ans %= kMod;    }    return ans;  }}; 

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 ↗