-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathBuild Array Where You Can Find The Maximum Exactly K Comparisons.cpp
67 lines (51 loc) · 1.83 KB
/
Build Array Where You Can Find The Maximum Exactly K Comparisons.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Solution by Rahul Surana
***********************************************************
You are given three integers n, m and k.
Consider the following algorithm to find the maximum element of an array of positive integers:
<code>
arr_max = -1, step = 0
for(auto z: arr)
if(arr_max < z)
arr_max = z
step++;
return step
</code>
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.
***********************************************************
*/
#define MOD 1000000007
class Solution {
public:
int numOfArrays(int n, int m, int k) {
if(m < k || k == 0) return 0;
vector<vector<long>> pdp(m+1,vector<long>(k+1,0));
vector<vector<long>> pps(m+1,vector<long>(k+1,0));
for(int i = 1; i < m+1; i++){
pdp[i][1] = 1;
pps[i][1] = i;
}
for(int _ = 2; _ < n+1; _++){
vector<vector<long>> dp(m+1,vector<long>(k+1,0));
vector<vector<long>> ps(m+1,vector<long>(k+1,0));
for(int i = 1; i < m+1; i++){
for(int j = 1; j < k+1; j++){
dp[i][j] = (i * pdp[i][j])%MOD;
if(j>1 && i >1){
dp[i][j] += pps[i-1][j-1];
dp[i][j] %= MOD;
}
ps[i][j] = (ps[i-1][j] + dp[i][j])%MOD;
}
}
pps = ps;
pdp = dp;
}
return pps[m][k];
}
};