Problem solution · Python

Build Array Where You Can Find The Maximum Exactly K Comparisons

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

  • 23 lines of Python from the credited upstream file 1420.py.
  • The implementation visibly relies on cached states.
  • No explicit 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 · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def numOfArrays(self, n: int, m: int, k: int) -> 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`    dp = [[[0] * (k + 1) for j in range(m + 1)] for _ in range(n + 1)]     for j in range(1, m + 1):      dp[1][j][1] = 1     for i in range(2, n + 1):  # for each length      for j in range(1, m + 1):  # for each max value        for cost in range(1, k + 1):  # 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] = j * dp[i - 1][j][cost] % MOD          # 2. Appending j in the i-th position makes j the new max and cost 1.          for prevMax in range(1, j):            dp[i][j][cost] += dp[i - 1][prevMax][cost - 1]            dp[i][j][cost] %= MOD     return sum(dp[n][j][k] for j in range(1, m + 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 ↗