Find Sum of Array Product of Magical Sequences Problem
Description
LeetCode Problem 3539.
You are given two integers, m and k, and an integer array nums.
A sequence of integers seq is called magical if:
seqhas a size ofm.0 <= seq[i] < nums.length- The binary representation of
2^(seq[0]) + 2^(seq[1]) + ... + 2^(seq[m - 1])haskset bits.
The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m - 1]]).
Return the sum of the array products for all valid magical sequences.
Since the answer may be large, return it modulo 10^9 + 7.
A set bit refers to a bit in the binary representation of a number that has a value of 1.
Example 1:
Input: m = 5, k = 5, nums = [1,10,100,10000,1000000]
Output: 991600007
Explanation:
All permutations of [0, 1, 2, 3, 4] are magical sequences, each with an array product of 10^13.
Example 2:
Input: m = 2, k = 2, nums = [5,4,3,2,1]
Output: 170
Explanation:
The magical sequences are [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 4], [4, 0], [4, 1], [4, 2], and [4, 3].
Example 3:
Input: m = 1, k = 1, nums = [28]
Output: 28
Explanation:
The only magical sequence is [0].
Constraints:
1 <= k <= m <= 301 <= nums.length <= 501 <= nums[i] <= 10^8
Solution
Approach: Combinatorics + Memoized Search
Define dfs(i, j, k, st): we are at nums[i], j positions of the sequence are still unfilled, k set bits are still needed in the binary sum, and st is the carry from lower bits. The answer is dfs(0, m, k, 0). If k < 0, or all numbers are used while j > 0, return 0. If all numbers are used, flush the remaining carry into k and return 1 when k reaches 0. Otherwise choose t of the j positions to hold nums[i] (0 <= t <= j): there are C(j, t) ways, the product contributes nums[i]^t, the current bit is (t + st) & 1 and the new carry is (t + st) >> 1. Sum over all t. Binomials come from precomputed factorials and inverse factorials modulo 10^9 + 7.
Complexity: O(n * m^3 * k) time and O(n * m^2 * k) extra space, where n is the length of nums, m and k are the problem parameters.
from functools import lru_cache
mx = 30
mod = 10**9 + 7
f = [1] + [0] * mx
g = [1] + [0] * mx
for i in range(1, mx + 1):
f[i] = f[i - 1] * i % mod
g[i] = pow(f[i], mod - 2, mod)
def comb(m: int, n: int) -> int:
return f[m] * g[n] * g[m - n] % mod
class Solution:
def magicalSum(self, m: int, k: int, nums: List[int]) -> int:
@lru_cache(None)
def dfs(i: int, j: int, k: int, st: int) -> int:
if k < 0 or (i == len(nums) and j > 0):
return 0
if i == len(nums):
while st:
k -= st & 1
st >>= 1
return int(k == 0)
res = 0
for t in range(j + 1):
nt = t + st
p = pow(nums[i], t, mod)
nk = k - (nt & 1)
res += comb(j, t) * p * dfs(i + 1, j - t, nk, nt >> 1)
res %= mod
return res
ans = dfs(0, m, k, 0)
dfs.cache_clear()
return ans