|
| 1 | +/** |
| 2 | + * 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons |
| 3 | + * https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given three integers n, m and k. Consider the following algorithm to find the maximum |
| 7 | + * element of an array of positive integers. |
| 8 | + * |
| 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 | + * |
| 14 | + * Return the number of ways to build the array arr under the mentioned conditions. As the answer |
| 15 | + * may grow large, the answer must be computed modulo 109 + 7. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @param {number} m |
| 21 | + * @param {number} k |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +function numOfArrays(length, maxValue, searchCost) { |
| 25 | + const MOD = 1e9 + 7; |
| 26 | + const cache = Array.from({ length: length + 1 }, () => |
| 27 | + Array.from({ length: maxValue + 1 }, () => |
| 28 | + Array(searchCost + 1).fill(-1) |
| 29 | + ) |
| 30 | + ); |
| 31 | + |
| 32 | + function computeArrays(pos, currentMax, remainingCost) { |
| 33 | + if (pos === length) return remainingCost === 0 ? 1 : 0; |
| 34 | + if (remainingCost < 0) return 0; |
| 35 | + if (cache[pos][currentMax][remainingCost] !== -1) { |
| 36 | + return cache[pos][currentMax][remainingCost]; |
| 37 | + } |
| 38 | + |
| 39 | + let total = 0; |
| 40 | + for (let value = 1; value <= currentMax; value++) { |
| 41 | + total = (total + computeArrays(pos + 1, currentMax, remainingCost)) % MOD; |
| 42 | + } |
| 43 | + |
| 44 | + if (remainingCost > 0) { |
| 45 | + for (let value = currentMax + 1; value <= maxValue; value++) { |
| 46 | + total = (total + computeArrays(pos + 1, value, remainingCost - 1)) % MOD; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return cache[pos][currentMax][remainingCost] = total; |
| 51 | + } |
| 52 | + |
| 53 | + let result = 0; |
| 54 | + for (let value = 1; value <= maxValue; value++) { |
| 55 | + result = (result + computeArrays(1, value, searchCost - 1)) % MOD; |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +} |
0 commit comments