11package g2901_3000.s2902_count_of_sub_multisets_with_bounded_sum
22
33// #Hard #Array #Hash_Table #Dynamic_Programming #Sliding_Window
4- // #2023_12_31_Time_249_ms_(100.00 %)_Space_41.2_MB_(100.00 %)
4+ // #2024_01_03_Time_263_ms_(87.50 %)_Space_41.5_MB_(37.50 %)
55
66import kotlin.math.min
77
88@Suppress(" NAME_SHADOWING" )
99class Solution {
10+ private val mod = 1000000007
11+ private val intMap = IntMap ()
12+
1013 fun countSubMultisets (nums : List <Int >, l : Int , r : Int ): Int {
11- var r = r
12- INT_MAP .clear()
13- INT_MAP .add(0 )
14+ intMap.clear()
15+ intMap.add(0 )
1416 var total = 0
1517 for (num in nums) {
16- INT_MAP .add(num)
18+ intMap .add(num)
1719 total + = num
1820 }
1921 if (total < l) {
2022 return 0
2123 }
22- r = min(r, total)
24+ val r = min(r, total)
2325 val cnt = IntArray (r + 1 )
24- cnt[0 ] = INT_MAP .map[0 ]
26+ cnt[0 ] = intMap .map[0 ]
2527 var sum = 0
26- for (i in 1 until INT_MAP .size) {
27- val ` val ` = INT_MAP .vals[i]
28- val count = INT_MAP .map[` val ` ]
28+ for (i in 1 until intMap .size) {
29+ val value = intMap .vals[i]
30+ val count = intMap .map[value ]
2931 if (count > 0 ) {
30- sum = min(r, sum + ` val ` * count)
31- update(cnt, ` val ` , count, sum)
32+ sum = min(r, sum + value * count)
33+ update(cnt, value , count, sum)
3234 }
3335 }
3436 var res = 0
3537 for (i in l.. r) {
36- res = (res + cnt[i]) % MOD
38+ res = (res + cnt[i]) % mod
3739 }
3840 return res
3941 }
4042
4143 private fun update (cnt : IntArray , n : Int , count : Int , sum : Int ) {
4244 if (count == 1 ) {
4345 for (i in sum downTo n) {
44- cnt[i] = (cnt[i] + cnt[i - n]) % MOD
46+ cnt[i] = (cnt[i] + cnt[i - n]) % mod
4547 }
4648 } else {
4749 for (i in n.. sum) {
48- cnt[i] = (cnt[i] + cnt[i - n]) % MOD
50+ cnt[i] = (cnt[i] + cnt[i - n]) % mod
4951 }
5052 val max = (count + 1 ) * n
5153 for (i in sum downTo max) {
52- cnt[i] = (cnt[i] - cnt[i - max] + MOD ) % MOD
54+ cnt[i] = (cnt[i] - cnt[i - max] + mod ) % mod
5355 }
5456 }
5557 }
5658
5759 private class IntMap {
58- val map: IntArray = IntArray (MAX )
59- val vals: IntArray = IntArray (MAX )
60- var size: Int = 0
60+ private val max = 20001
61+ val map = IntArray (max)
62+ val vals = IntArray (max)
63+ var size = 0
6164
6265 fun add (v : Int ) {
6366 if (map[v]++ == 0 ) {
@@ -72,10 +75,4 @@ class Solution {
7275 size = 0
7376 }
7477 }
75-
76- companion object {
77- private const val MOD = 1000000007
78- private const val MAX = 20001
79- private val INT_MAP = IntMap ()
80- }
8178}
0 commit comments