LeetCode 3251: Find the Count of Monotonic Pairs II Solution
Master LeetCode problem 3251 (Find the Count of Monotonic Pairs II), 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.
3251. Find the Count of Monotonic Pairs II
Problem Explanation
Explanation:
To solve this problem, we can iterate through all possible values for arr1[0] and arr2[0], and then recursively calculate the counts for the rest of the elements in arr1 and arr2 while making sure that the conditions for monotonic pairs hold. We can use dynamic programming to store and reuse the counts for subproblems.
- Initialize a 2D array
dpof size n x 1000 x 1000 to store the counts. - Define a recursive function
countPairswhich takes the current indexidx, the current values ofarr1andarr2, and returns the count of monotonic pairs that can be formed. - Inside the function, if the current index is the last index, check if the values satisfy the conditions and return 1 if true, else return 0.
- Otherwise, iterate through all possible values for
arr1[idx]andarr2[idx], and recursively call the function for the next index. - Store the count in the
dparray to avoid recomputation. - Finally, return the total count of monotonic pairs.
Time complexity: O(n * 1000^2) where n is the length of the input array. Space complexity: O(n * 1000^2) for the dp array.
:
Solution Code
class Solution {
int MOD = 1000000007;
public int countPairs(int[] nums) {
int n = nums.length;
long[][][] dp = new long[n][1001][1001];
return (int) countPairs(0, nums, 0, 0, dp);
}
private long countPairs(int idx, int[] nums, int val1, int val2, long[][][] dp) {
if (idx == nums.length) {
return 1;
}
if (dp[idx][val1][val2] != 0) {
return dp[idx][val1][val2];
}
long count = 0;
for (int i = val1; i <= nums[idx]; i++) {
for (int j = val2; j >= i; j--) {
count = (count + countPairs(idx + 1, nums, i, j, dp)) % MOD;
}
}
dp[idx][val1][val2] = count;
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3251 (Find the Count of Monotonic Pairs II)?
This page provides optimized solutions for LeetCode problem 3251 (Find the Count of Monotonic Pairs II) 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 3251 (Find the Count of Monotonic Pairs II)?
The time complexity for LeetCode 3251 (Find the Count of Monotonic Pairs II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3251 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3251 in Java, C++, or Python.