Skip to main content
Back to problems
#1420
Hard Algorithms

Build array where you can find the maximum exactly k comparisons

Dynamic Programming Prefix Sum
65.9% acceptance
Feb 25, 2026
1461
94
You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers. 1 <= arr[i] <= m where (0 <= i < n). After applying the mentioned algorithm to arr, the value search_cost is equal to k. Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn num_of_arrays(n: i32, m: i32, k: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let (n, m, k) = (n as usize, m as usize, k as usize);
    // dp[max_val][cost] = number of arrays of current length with max=max_val and search_cost=cost
    let mut dp = vec![vec![0i64; k + 1]; m + 1];
    dp[0][0] = 1; // empty array: max=0, cost=0
    for _ in 0..n {
      let mut new_dp = vec![vec![0i64; k + 1]; m + 1];
      for j in 0..=m {
        for s in 0..=k {
          if dp[j][s] == 0 { continue; }
          // append v = 1..=j (max stays j, cost stays s)
          new_dp[j][s] = (new_dp[j][s] + dp[j][s] * j as i64) % MOD;
          // append v = j+1..=m (max becomes v, cost becomes s+1)
          if s + 1 <= k {
            for v in j+1..=m {
              new_dp[v][s+1] = (new_dp[v][s+1] + dp[j][s]) % MOD;
            }
          }
        }
      }
      dp = new_dp;
    }
    let mut result = 0i64;
    for j in 1..=m {
      result = (result + dp[j][k]) % MOD;
    }
    result as i32
  }
}