Find the Count of Monotonic Pairs I - Problem

You are given an array of positive integers nums of length n. Your task is to find the number of ways to split each element of nums into two non-negative integers such that:

  • The first part forms a monotonically non-decreasing array
  • The second part forms a monotonically non-increasing array

More formally, we need to count pairs of arrays (arr1, arr2) where:

  • Both arrays have length n
  • arr1[0] ≤ arr1[1] ≤ ... ≤ arr1[n-1] (non-decreasing)
  • arr2[0] ≥ arr2[1] ≥ ... ≥ arr2[n-1] (non-increasing)
  • arr1[i] + arr2[i] == nums[i] for all positions

Example: If nums = [2, 3, 2], one valid pair is arr1 = [0, 1, 1] and arr2 = [2, 2, 1] because 0+2=2, 1+2=3, 1+1=2, and the monotonicity conditions are satisfied.

Return the count modulo 10^9 + 7.

Input & Output

example_1.py — Basic Case
$ Input: [2, 3, 2]
Output: 4
💡 Note: The 4 valid pairs are: ([0,0,0],[2,3,2]), ([0,1,1],[2,2,1]), ([1,1,1],[1,2,1]), ([2,3,2],[0,0,0]). Each satisfies arr1 non-decreasing and arr2 non-increasing.
example_2.py — Single Element
$ Input: [5]
Output: 6
💡 Note: With one element, arr1 can be [0],[1],[2],[3],[4], or [5], and arr2 will be [5],[4],[3],[2],[1], or [0] respectively. All are valid since single-element arrays are trivially monotonic.
example_3.py — Increasing Sequence
$ Input: [2, 3, 4]
Output: 6
💡 Note: Valid pairs include ([0,0,0],[2,3,4]), ([0,0,1],[2,3,3]), ([0,1,1],[2,2,3]), ([0,1,2],[2,2,2]), ([1,1,1],[1,2,3]), ([2,3,4],[0,0,0]). The constraints limit the valid combinations.

Constraints

  • 1 ≤ n ≤ 2000
  • 1 ≤ nums[i] ≤ 50
  • All elements of nums are positive integers
  • Answer should be returned modulo 109 + 7

Visualization

Tap to expand
Water Distribution SystemGroundReservoirElevatedTankBuilding 1needsnums[0]Building 2Building 3arr1[i] (non-decreasing)arr2[i] (non-increasing)Each building gets: Ground[i] + Elevated[i] = nums[i]Ground pressure must increase or stay sameElevated pressure must decrease or stay same
Understanding the Visualization
1
Setup
Each building needs exactly nums[i] units of water from two sources
2
Constraints
Ground pressure can only increase, elevated pressure can only decrease
3
Count
Find all valid pressure distribution patterns
Key Takeaway
🎯 Key Insight: Use dynamic programming to track valid ground pressure levels at each position, automatically determining elevated pressure to satisfy building demands while maintaining system constraints.
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 5
28.9K Views
Medium Frequency
~35 min Avg. Time
847 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