LeetCode 2338: Count the Number of Ideal Arrays Solution
Master LeetCode problem 2338 (Count the Number of Ideal Arrays), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2338. Count the Number of Ideal Arrays
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will iterate through all possible values from 1 to maxValue for each position in the array and keep track of the count of distinct ideal arrays that can be formed.
- Initialize a 2D array dp of size n x (maxValue + 1) where dp[i][j] represents the count of distinct ideal arrays of length i ending with value j.
- Initialize dp[1][j] as 1 for all 1 <= j <= maxValue, as there is only one ideal array of length 1 ending with each value j.
- For each position i from 2 to n, iterate through all values from 1 to maxValue. For each value j, calculate dp[i][j] by summing up dp[i-1][k] for all k such that j % k == 0.
- The total count of distinct ideal arrays of length n will be the sum of all values in the last row of the dp array.
- Return this count modulo 10^9 + 7 as the final answer.
Time Complexity: O(n * maxValue^2) Space Complexity: O(n * maxValue)
Solution Code
class Solution {
public int countIdealArrays(int n, int maxValue) {
int MOD = 1000000007;
int[][] dp = new int[n + 1][maxValue + 1];
for (int j = 1; j <= maxValue; j++) {
dp[1][j] = 1;
}
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= maxValue; j++) {
for (int k = 1; k <= maxValue; k++) {
if (j % k == 0) {
dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD;
}
}
}
}
int result = 0;
for (int j = 1; j <= maxValue; j++) {
result = (result + dp[n][j]) % MOD;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2338 (Count the Number of Ideal Arrays)?
This page provides optimized solutions for LeetCode problem 2338 (Count the Number of Ideal Arrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2338 (Count the Number of Ideal Arrays)?
The time complexity for LeetCode 2338 (Count the Number of Ideal Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2338 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2338 in Java, C++, or Python.