Problem solution · Java

Build Array Where You Can Find The Maximum Exactly K Comparisons

Build Array Where You Can Find The Maximum Exactly K Comparisons: 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
32 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

  • 32 lines of Java from the credited upstream file 1420.java.
  • 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 · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int numOfArrays(int n, int m, int k) {    final int MOD = 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`    int[][][] dp = new int[n + 1][m + 1][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] = (int) ((long) j * dp[i - 1][j][cost] % MOD);          // 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] %= MOD;          }        }     int ans = 0;    for (int j = 1; j <= m; ++j) {      ans += dp[n][j][k];      ans %= MOD;    }    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 ↗