Find the Count of Monotonic Pairs II - Problem
Imagine you have an array of positive integers and need to decompose each number into two parts that follow opposite trends across the array.
Given an array nums of length n, you need to find how many ways you can create two arrays:
- arr1: A non-decreasing sequence (values stay same or increase)
- arr2: A non-increasing sequence (values stay same or decrease)
The key constraint: arr1[i] + arr2[i] = nums[i] for every position i.
Example: If nums = [2, 3, 2], one valid pair could be:
arr1 = [0, 1, 1](non-decreasing: 0 ≤ 1 ≤ 1)arr2 = [2, 2, 1](non-increasing: 2 ≥ 2 ≥ 1)- Check:
[0+2, 1+2, 1+1] = [2, 3, 2] ✓
Return the total count of such monotonic pairs modulo 10^9 + 7.
Input & Output
example_1.py — Basic Case
$
Input:
nums = [2, 3, 2]
›
Output:
4
💡 Note:
Valid pairs: ([0,1,1],[2,2,1]), ([0,2,2],[2,1,0]), ([1,2,2],[1,1,0]), ([2,3,2],[0,0,0])
example_2.py — Single Element
$
Input:
nums = [5]
›
Output:
6
💡 Note:
For single element, arr1 can be 0,1,2,3,4,5 and arr2 will be 5,4,3,2,1,0 respectively. All 6 combinations are valid.
example_3.py — Increasing Sequence
$
Input:
nums = [5, 5, 5, 5]
›
Output:
126
💡 Note:
With identical values, we have maximum flexibility in distribution while maintaining monotonic constraints.
Constraints
- 1 ≤ nums.length ≤ 2000
- 1 ≤ nums[i] ≤ 1000
- Both arr1 and arr2 contain non-negative integers
- Time limit: 2 seconds
Visualization
Tap to expand
Understanding the Visualization
1
Start with constraints
arr1 must be non-decreasing, arr2 must be non-increasing
2
Try all combinations
For each position, split nums[i] between arr1[i] and arr2[i]
3
Check validity
Ensure monotonic properties are maintained
4
Count solutions
Sum all valid complete decompositions
Key Takeaway
🎯 Key Insight: Use DP to systematically explore all valid decompositions while respecting monotonic constraints, memoizing intermediate results to avoid redundant computation.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code