Find the Count of Monotonic Pairs II - Problem

You are given an array of positive integers nums of length n.

We call a pair of non-negative integer arrays (arr1, arr2) monotonic if:

  • The lengths of both arrays are n.
  • arr1 is monotonically non-decreasing, in other words, arr1[0] <= arr1[1] <= ... <= arr1[n - 1].
  • arr2 is monotonically non-increasing, in other words, arr2[0] >= arr2[1] >= ... >= arr2[n - 1].
  • arr1[i] + arr2[i] == nums[i] for all 0 <= i <= n - 1.

Return the count of monotonic pairs. Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,2]
Output: 4
💡 Note: Valid monotonic pairs: ([0,2,1],[2,1,1]), ([0,2,2],[2,1,0]), ([0,3,1],[2,0,1]), ([0,3,2],[2,0,0]). Each satisfies arr1 non-decreasing, arr2 non-increasing, and arr1[i] + arr2[i] = nums[i].
Example 2 — Single Element
$ Input: nums = [5]
Output: 6
💡 Note: For single element, arr1[0] can be 0,1,2,3,4,5 and arr2[0] = 5-arr1[0]. All 6 combinations are valid since there are no monotonic constraints to check.
Example 3 — Identical Elements
$ Input: nums = [2,2]
Output: 6
💡 Note: Valid pairs include ([0,0],[2,2]), ([0,1],[2,1]), ([0,2],[2,0]), ([1,1],[1,1]), ([1,2],[1,0]), ([2,2],[0,0]). Total count is 6.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Monotonic Pairs Problem: nums = [2,3,2]232Input: nums array021211arr1 (↗)arr2 (↘)032200Valid Pair 1: ([0,2,1], [2,1,1])Valid Pair 2: ([0,3,2], [2,0,0])Total valid monotonic pairs: 4Split + Constrain + Count
Understanding the Visualization
1
Input Array
Given nums = [2,3,2]
2
Split Each Element
nums[i] = arr1[i] + arr2[i]
3
Apply Constraints
arr1 non-decreasing, arr2 non-increasing
4
Count Valid Pairs
Total monotonic pairs
Key Takeaway
🎯 Key Insight: Transform the splitting problem into dynamic programming with monotonic constraints
Asked in
Google 15 Facebook 12 Amazon 8
26.7K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen