|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons |
| 4 | +# Hard |
| 5 | +# https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: |
| 9 | +You should build the array arr which has the following properties: |
| 10 | +* arr has exactly n integers. |
| 11 | +* 1 <= arr[i] <= m where (0 <= i < n). |
| 12 | +* After applying the mentioned algorithm to arr, the value search_cost is equal to k. |
| 13 | +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. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: n = 2, m = 3, k = 1 |
| 17 | +Output: 6 |
| 18 | +Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] |
| 19 | +
|
| 20 | +Example 2: |
| 21 | +Input: n = 5, m = 2, k = 3 |
| 22 | +Output: 0 |
| 23 | +Explanation: There are no possible arrays that satisify the mentioned conditions. |
| 24 | +
|
| 25 | +Example 3: |
| 26 | +Input: n = 9, m = 1, k = 1 |
| 27 | +Output: 1 |
| 28 | +Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1] |
| 29 | +
|
| 30 | +Constraints: |
| 31 | +* 1 <= n <= 50 |
| 32 | +* 1 <= m <= 100 |
| 33 | +* 0 <= k <= n |
| 34 | +=end |
| 35 | + |
| 36 | +# @param {Integer} n |
| 37 | +# @param {Integer} m |
| 38 | +# @param {Integer} k |
| 39 | +# @return {Integer} |
| 40 | +MOD = 1_000_000_007 |
| 41 | + |
| 42 | +def num_of_arrays(n, m, k) |
| 43 | + dp = Array.new(n + 1) { Array.new(m + 1) { Array.new(k + 1, 0) } } |
| 44 | + |
| 45 | + 1.upto(m) do |i| |
| 46 | + dp[1][i][1] = 1 |
| 47 | + end |
| 48 | + |
| 49 | + 2.upto(n) do |len| |
| 50 | + 1.upto(m) do |max_val| |
| 51 | + 1.upto(k) do |cost| |
| 52 | + sum = 0 |
| 53 | + 1.upto(max_val - 1) do |i| |
| 54 | + sum = (sum + dp[len - 1][i][cost - 1]) % MOD |
| 55 | + end |
| 56 | + dp[len][max_val][cost] = (dp[len - 1][max_val][cost] * max_val + sum) % MOD |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + ans = 0 |
| 62 | + 1.upto(m) do |i| |
| 63 | + ans = (ans + dp[n][i][k]) % MOD |
| 64 | + end |
| 65 | + |
| 66 | + ans |
| 67 | +end |
| 68 | + |
| 69 | +# **************** # |
| 70 | +# TEST # |
| 71 | +# **************** # |
| 72 | + |
| 73 | +require "test/unit" |
| 74 | +class Test_num_of_arrays < Test::Unit::TestCase |
| 75 | + def test_ |
| 76 | + assert_equal 6, num_of_arrays(2, 3, 1) |
| 77 | + assert_equal 0, num_of_arrays(5, 2, 3) |
| 78 | + assert_equal 1, num_of_arrays(9, 1, 1) |
| 79 | + end |
| 80 | +end |
0 commit comments