Count Non Decreasing Arrays With Given Digit Sums Problem
Description
LeetCode Problem 3883.
You are given an integer array digitSum of length n.
An array arr of length n is considered valid if:
0 <= arr[i] <= 5000- it is non-decreasing.
- the sum of the digits of
arr[i]equalsdigitSum[i].
Return an integer denoting the number of distinct valid arrays. Since the answer may be large, return it modulo 10^9 + 7.
An array is said to be non-decreasing if each element is greater than or equal to the previous element, if it exists.
Example 1:
Input: digitSum = [25,1]
Output: 6
Explanation:
Numbers whose sum of digits is 25 are 799, 889, 898, 979, 988, and 997.
The only number whose sum of digits is 1 that can appear after these values while keeping the array non-decreasing is 1000.
Thus, the valid arrays are [799, 1000], [889, 1000], [898, 1000], [979, 1000], [988, 1000], and [997, 1000].
Hence, the answer is 6.
Example 2:
Input: digitSum = [1]
Output: 4
Explanation:
The valid arrays are [1], [10], [100], and [1000].
Thus, the answer is 4.
Example 3:
Input: digitSum = [2,49,23]
Output: 0
Explanation:
There is no integer in the range [0, 5000] whose sum of digits is 49. Thus, the answer is 0.
Constraints:
1 <= digitSum.length <= 10000 <= digitSum[i] <= 50
Solution
Approach: Dynamic Programming + Prefix Sums
Values are limited to 0..5000, so first group the numbers by digit sum: cand[s] lists every value in that range whose digits add up to s.
Let dp[v] be the number of valid prefixes whose last element is v. For index 0, dp[v] = 1 for every v in cand[digitSum[0]]. For each later index, a value v in cand[digitSum[i]] can follow any previous value u <= v, so dp_new[v] = dp[0] + dp[1] + ... + dp[v]. A running prefix sum gives all of these in one pass over 0..5000; every other v gets 0.
The answer is the sum of dp after the last index, modulo 10^9 + 7. If some digit sum has no candidates (for example 49), all dp entries become 0.
Complexity: time O(n * 5001), space O(5001), where n is the length of digitSum.
from itertools import accumulate
class Solution:
def countArrays(self, digitSum: List[int]) -> int:
MOD = 10**9 + 7
M = 5001
cand = [[] for _ in range(51)]
for v in range(M):
s = sum(map(int, str(v)))
if s <= 50:
cand[s].append(v)
dp = [0] * M
for v in cand[digitSum[0]]:
dp[v] = 1
for s in digitSum[1:]:
pre = list(accumulate(dp))
dp = [0] * M
for v in cand[s]:
dp[v] = pre[v] % MOD
return sum(dp) % MOD