Skip to content

Commit 547e12f

Browse files
committed
1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
1 parent fd6fc6f commit 547e12f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
5+
6+
// The runtime of this solution is O(NKM^2)
7+
// but you can achieve O(NKM * log(M)) with a Fenwick tree
8+
// or O(NKM) by using prefix sums and eliminating the innermost for-loop
9+
10+
func numOfArrays(_ n: Int, _ m: Int, _ k: Int) -> Int {
11+
let MOD = 1_000_000_007
12+
13+
var ways = Array(
14+
repeating: Array(repeating: Array(repeating: 0, count: k + 1), count: m + 1),
15+
count: n + 1)
16+
17+
// Base cases: ways[1][j][1] = 1 for all j from 1 to m.
18+
for j in 1...m {
19+
ways[1][j][1] = 1
20+
}
21+
22+
for a in 1...n {
23+
for b in 1...m {
24+
for c in 1...k {
25+
var s: Int = 0
26+
27+
// First case: Append any element from [1, b] to the end of the array.
28+
s = (s + b * ways[a - 1][b][c]) % MOD
29+
30+
// Second case: Append the element "b" to the end of the array.
31+
for x in 1..<b {
32+
s = (s + ways[a - 1][x][c - 1]) % MOD
33+
}
34+
35+
ways[a][b][c] = (ways[a][b][c] + s) % MOD
36+
}
37+
}
38+
}
39+
40+
var ans: Int = 0
41+
42+
for j in 1...m {
43+
ans = (ans + ways[n][j][k]) % MOD
44+
}
45+
46+
return ans
47+
}
48+
}

0 commit comments

Comments
 (0)