Skip to content

Commit c0f06b1

Browse files
committed
Improved task
1 parent 9abc5aa commit c0f06b1

File tree

1 file changed

+26
-28
lines changed
  • src/main/kotlin/g3501_3600/s3539_find_sum_of_array_product_of_magical_sequences

1 file changed

+26
-28
lines changed
Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
package g3501_3600.s3539_find_sum_of_array_product_of_magical_sequences
22

33
// #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%)
55

66
class Solution {
7+
private val mod = 1000000007
8+
private val c: Array<IntArray> = precomputeBinom(31)
9+
private val p: IntArray = precomputePop(31)
10+
711
fun magicalSum(m: Int, k: Int, nums: IntArray): Int {
812
val n = nums.size
913
val pow = Array<LongArray>(n) { LongArray(m + 1) }
1014
for (j in 0..<n) {
1115
pow[j][0] = 1L
1216
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
1418
}
1519
}
1620
var dp = Array<Array<LongArray>>(m + 1) { Array<LongArray>(k + 1) { LongArray(m + 1) } }
@@ -38,12 +42,12 @@ class Solution {
3842
(
3943
next[t + cc][o + (total and 1)][total ushr 1] +
4044
dp[t][o][c] *
41-
C[m - t][cc] %
42-
MOD
45+
this@Solution.c[m - t][cc] %
46+
mod
4347
* pow[i][cc] %
44-
MOD
48+
mod
4549
) %
46-
MOD
50+
mod
4751
)
4852
}
4953
}
@@ -56,37 +60,31 @@ class Solution {
5660
var res: Long = 0
5761
for (o in 0..k) {
5862
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
6165
}
6266
}
6367
}
6468
return res.toInt()
6569
}
6670

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
8078
}
81-
return res
8279
}
80+
return res
81+
}
8382

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)
9087
}
88+
return res
9189
}
9290
}

0 commit comments

Comments
 (0)