2023-10-07 Daily Challenge
Today I have done leetcode's October LeetCoding Challenge with cpp
.
October LeetCoding Challenge 7
Description
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 exactlyn
integers.1 <= arr[i] <= m
where(0 <= i < n)
.- After applying the mentioned algorithm to
arr
, the valuesearch_cost
is equal tok
.
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
.
Example 1:
Input: n = 2, m = 3, k = 1 Output: 6 Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
Example 2:
Input: n = 5, m = 2, k = 3 Output: 0 Explanation: There are no possible arrays that satisify the mentioned conditions.
Example 3:
Input: n = 9, m = 1, k = 1 Output: 1 Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n
Solution
class Solution {
public:
int numOfArrays(int n, int m, int k) {
const int MOD = 1e9 + 7;
int dp[51][101][51] = {};
int pre[51][101][51] = {};
for(int i = 0; i <= m; ++i) {
dp[1][i][1] = 1;
pre[1][i][1] = i;
}
for(int len = 2; len <= n; ++len) {
for(int mmax = 1; mmax <= m; ++mmax) {
for(int cost = 1; cost <= k; ++cost) {
dp[len][mmax][cost] = (1LL * mmax * dp[len - 1][mmax][cost]) % MOD;
dp[len][mmax][cost] += pre[len - 1][mmax - 1][cost - 1];
dp[len][mmax][cost] %= MOD;
pre[len][mmax][cost] = pre[len][mmax - 1][cost] + dp[len][mmax][cost];
pre[len][mmax][cost] %= MOD;
}
}
}
return pre[n][m][k];
}
};
// Accepted
// 28/28 cases passed (3 ms)
// Your runtime beats 98.62 % of cpp submissions
// Your memory usage beats 43.32 % of cpp submissions (8.5 MB)