Non Decreasing Arrays With Given Digit Sums

You are given an array digitSum of length n. You need to construct an array arr of the same length such that:

  • Every element in arr is between 0 and 5000 (inclusive).
  • The array is strictly non-decreasing (arr[i] >= arr[i-1]).
  • The sum of the digits of arr[i] is exactly equal to digitSum[i].

Return the total number of distinct valid arrays you can form, modulo 109 + 7.

Your task is to Count all valid monotonic arrays that satisfy those digit sums.

Example 1:

Input: digitSum = [25, 1]

Output: 6

Explanation:

- Numbers up to 5000 whose digit sum is 25: 799, 889, 898, 979, 988, 997, 1996, 2896...

- The target for the second number is a digit sum of 1 (1, 10, 100, 1000).

- Because the array must be non-decreasing, the second number must be >= the first.

- The only valid second number is 1000.

- The first number must be <= 1000, leaving exactly six options: [799, 1000], [889, 1000], [898, 1000], [979, 1000], [988, 1000], [997, 1000].

Example 2:

Input: digitSum = [2, 49, 23]

Output: 0

Explanation:

The maximum possible digit sum for any number between 0 and 5000 is 31 (which comes from the number 4999 -> 4+9+9+9). Therefore, there are absolutely zero numbers that satisfy the target digit sum of 49. The chain breaks, resulting in 0 arrays.

Now Your Turn!

Pick the correct output for the given input

Input: digitSum = [1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= digitSum.length <= 1000
  • 0 <= digitSum[i] <= 50

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int countNonDecreasingArrays(vector<int>& digitSum) {
// Write your code here
}
};
Test Case

Input:

Digit Sum