Problem
You are given two integers n
and maxValue
, which are used to describe an ideal array.
A 0-indexed integer array arr
of length n
is considered ideal if the following conditions hold:
- Every
arr[i]
is a value from1
tomaxValue
, for0 <= i < n
. - Every
arr[i]
is divisible byarr[i - 1]
, for0 < i < n
.
Return the number of distinct ideal arrays of length n
. Since the answer may be very large, return it modulo 10^9 + 7
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= n <= 10^4
1 <= maxValue <= 10^4
Solution
Method 1 - Maths + DP
The problem asks us to count distinct ideal arrays of length n
. An array arr
is ideal if:
- Every
arr[i]
lies between1
andmaxValue
. - Every element
arr[i]
is divisible byarr[i - 1]
for indicesi > 0
.
To solve this:
- We consider dynamic programming (
DP
) and precomputation using combinations to avoid redundant calculations. - The array’s construction follows a tree-like structure where each node (representing a number) connects to its multiples.
Here are the steps:
- For each length
1 <= len <= n
, calculate the number of arrays originating from each element in1 to maxValue
. - Use a DP table
dp[j][k]
:dp[j][k]
is the number of valid arrays of lengthj
with last elementk
. - Populate the DP table by considering that
dp[j][k]
depends on the values at the previous length (j - 1
) that are divisors ofk
. - Incorporate precomputed combinations for efficiency while managing results modulo
10^9 + 7
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity: -
O(n × maxValue × log(maxValue))
: DP computation requires iterating over divisors, which takes logarithmic time. - 🧺 Space complexity:
O(n × maxValue)
for The DP table size.