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
Count of Monotonic Pairs II INPUT nums array: 2 i=0 3 i=1 2 i=2 Constraints: arr1: non-decreasing arr2: non-increasing arr1[i] + arr2[i] = nums[i] Example pair: arr1 = [0, 1, 1] arr2 = [2, 2, 1] sum = [2, 3, 2] OK ALGORITHM STEPS 1 Initialize DP dp[v] = ways for arr1[0]=v 2 Prefix Sum Opt Use prefix sums for O(1) 3 Transition Check monotonic bounds 4 Sum Results Total valid pairs mod 10^9+7 DP Transition Table i=0: dp[0,1,2] = [1,1,1] i=1: dp[0,1,2,3] = [1,1,1,1] i=2: dp[0,1,2] = [1,2,1] Sum = 1+2+1 = 4 FINAL RESULT Valid Monotonic Pairs: 4 All 4 Valid Pairs: 1. arr1=[0,0,0] arr2=[2,3,2] 2. arr1=[0,1,1] arr2=[2,2,1] 3. arr1=[0,1,2] arr2=[2,2,0] 4. arr1=[0,0,1] arr2=[2,3,1] All constraints satisfied! Answer: 4 mod (10^9+7) = 4 Key Insight: The constraint arr2[i] = nums[i] - arr1[i] transforms the problem: if arr1 is non-decreasing and arr2 non-increasing, then arr1[i+1] >= arr1[i] AND (nums[i+1]-arr1[i+1]) <= (nums[i]-arr1[i]). Use prefix sums for O(n*max) complexity. TutorialsPoint - Find the Count of Monotonic Pairs II | Optimized DP with Prefix Sum
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