[LeetCode] Build Array Where You Can Find The Maximum Exactly K Comparisons

1420. Build Array Where You Can Find The Maximum Exactly K Comparisons

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
long long dp[51][101][51]{0,};
int mod = 1e9 + 7;
long long dfs(int n, int m, int k, int i, int v) {
if(n==i) return !k;
if(k<0) return 0;
if(dp[i][v][k]) return dp[i][v][k]-1;
dp[i][v][k] = 1;

for(int a = 1; a <= m; a++) {
dp[i][v][k] = (dp[i][v][k] + dfs(n,m,k - (a > v),i+1,max(v,a))) % mod;
}

return dp[i][v][k]-1;
}
public:
int numOfArrays(int n, int m, int k) {
return dfs(n,m,k,0,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/28/PS/LeetCode/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.