1
1
package g3501_3600.s3539_find_sum_of_array_product_of_magical_sequences
2
2
3
3
// #Hard #Array #Dynamic_Programming #Math #Bit_Manipulation #Bitmask #Combinatorics
4
- // #2025_05_04_Time_58_ms_(_%)_Space_49.73_MB_(_ %)
4
+ // #2025_05_06_Time_60_ms_(100.00%)_Space_48.98_MB_(100.00 %)
5
5
6
6
class Solution {
7
+ private val mod = 1000000007
8
+ private val c: Array <IntArray > = precomputeBinom(31 )
9
+ private val p: IntArray = precomputePop(31 )
10
+
7
11
fun magicalSum (m : Int , k : Int , nums : IntArray ): Int {
8
12
val n = nums.size
9
13
val pow = Array <LongArray >(n) { LongArray (m + 1 ) }
10
14
for (j in 0 .. < n) {
11
15
pow[j][0 ] = 1L
12
16
for (c in 1 .. m) {
13
- pow[j][c] = pow[j][c - 1 ] * nums[j] % MOD
17
+ pow[j][c] = pow[j][c - 1 ] * nums[j] % mod
14
18
}
15
19
}
16
20
var dp = Array <Array <LongArray >>(m + 1 ) { Array <LongArray >(k + 1 ) { LongArray (m + 1 ) } }
@@ -38,12 +42,12 @@ class Solution {
38
42
(
39
43
next[t + cc][o + (total and 1 )][total ushr 1 ] +
40
44
dp[t][o][c] *
41
- C [m - t][cc] %
42
- MOD
45
+ this @Solution.c [m - t][cc] %
46
+ mod
43
47
* pow[i][cc] %
44
- MOD
48
+ mod
45
49
) %
46
- MOD
50
+ mod
47
51
)
48
52
}
49
53
}
@@ -56,37 +60,31 @@ class Solution {
56
60
var res: Long = 0
57
61
for (o in 0 .. k) {
58
62
for (c in 0 .. m) {
59
- if (o + P [c] == k) {
60
- res = (res + dp[m][o][c]) % MOD
63
+ if (o + p [c] == k) {
64
+ res = (res + dp[m][o][c]) % mod
61
65
}
62
66
}
63
67
}
64
68
return res.toInt()
65
69
}
66
70
67
- companion object {
68
- private const val MOD = 1000000007
69
- private val C : Array <IntArray > = precomputeBinom(31 )
70
- private val P : IntArray = precomputePop(31 )
71
-
72
- private fun precomputeBinom (max : Int ): Array <IntArray > {
73
- val res = Array <IntArray >(max) { IntArray (max) }
74
- for (i in 0 .. < max) {
75
- res[i][i] = 1
76
- res[i][0 ] = res[i][i]
77
- for (j in 1 .. < i) {
78
- res[i][j] = (res[i - 1 ][j - 1 ] + res[i - 1 ][j]) % MOD
79
- }
71
+ private fun precomputeBinom (max : Int ): Array <IntArray > {
72
+ val res = Array <IntArray >(max) { IntArray (max) }
73
+ for (i in 0 .. < max) {
74
+ res[i][i] = 1
75
+ res[i][0 ] = res[i][i]
76
+ for (j in 1 .. < i) {
77
+ res[i][j] = (res[i - 1 ][j - 1 ] + res[i - 1 ][j]) % mod
80
78
}
81
- return res
82
79
}
80
+ return res
81
+ }
83
82
84
- private fun precomputePop (max : Int ): IntArray {
85
- val res = IntArray (max)
86
- for (i in 1 .. < max) {
87
- res[i] = res[i shr 1 ] + (i and 1 )
88
- }
89
- return res
83
+ private fun precomputePop (max : Int ): IntArray {
84
+ val res = IntArray (max)
85
+ for (i in 1 .. < max) {
86
+ res[i] = res[i shr 1 ] + (i and 1 )
90
87
}
88
+ return res
91
89
}
92
90
}
0 commit comments