Find the Count of Monotonic Pairs I - 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,1,1],[2,2,1]), ([0,1,2],[2,2,0]), ([0,2,2],[2,1,0]), ([1,2,2],[1,1,0]). Each satisfies arr1 non-decreasing and arr2 non-increasing constraints.
Example 2 — Minimum Size
$ Input: nums = [5,5]
Output: 21
💡 Note: For nums=[5,5], we need arr1 non-decreasing and arr2 non-increasing. There are 21 valid monotonic pairs total: for each valid arr1[0] value from 0 to 5, we count valid arr1[1] values that maintain both monotonic constraints.
Example 3 — Single Element
$ Input: nums = [3]
Output: 4
💡 Note: Single position allows arr1 values 0,1,2,3 with corresponding arr2 values 3,2,1,0. All are valid since no monotonic constraints between positions.

Constraints

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

Visualization

Tap to expand
Count of Monotonic Pairs - Bottom-Up DP INPUT nums array: 2 i=0 3 i=1 2 i=2 Conditions: arr1: non-decreasing arr2: non-increasing arr1[i] + arr2[i] = nums[i] Valid Pairs Example: arr1=[0,1,1], arr2=[2,2,1] arr1=[0,1,2], arr2=[2,2,0] arr1=[0,2,2], arr2=[2,1,0] arr1=[0,3,2]? Invalid! n = 3, max value = 3 ALGORITHM STEPS 1 Define DP State dp[i][v] = count where arr1[i]=v 2 Base Case (i=0) dp[0][v]=1 for v in [0,nums[0]] 3 Transition Check arr1 inc, arr2 dec 4 Sum Final Row Answer = sum(dp[n-1][*]) DP Table (partial): i\v 0 1 2 3 0 1 1 1 - 1 1 2 3 3 2 0 1 3 - Sum row 2: 0+1+3 = 4 Modulo: 10^9 + 7 FINAL RESULT Count of Pairs 4 OK All 4 Valid Pairs: Pair 1: arr1=[0,1,1] arr2=[2,2,1] Pair 2: arr1=[0,1,2] arr2=[2,2,0] Pair 3: arr1=[0,2,2] arr2=[2,1,0] Pair 4: arr1=[0,3,2] arr2=[2,0,0] All satisfy constraints! Key Insight: For each position i, if arr1[i] = v, then arr2[i] = nums[i] - v. The DP transition requires: prev_v <= curr_v (arr1 non-decreasing) AND nums[i-1]-prev_v >= nums[i]-curr_v (arr2 non-increasing). This simplifies to: prev_v <= curr_v AND prev_v <= curr_v + nums[i-1] - nums[i]. Time: O(n * max(nums)^2) TutorialsPoint - Find the Count of Monotonic Pairs I | Bottom-Up Dynamic Programming
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
12.5K Views
Medium Frequency
~35 min Avg. Time
285 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