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 modulo109 + 7.
Example 1:
Input:nums = [2,3,2]
Output:4
Explanation:
The good pairs are:
([0, 1, 1], [2, 2, 1])
([0, 1, 2], [2, 2, 0])
([0, 2, 2], [2, 1, 0])
([1, 2, 2], [1, 1, 0])
Example 2:
Input:nums = [5,5,5,5]
Output:126
Constraints:
1 <= n == nums.length <= 2000
1 <= nums[i] <= 50
Solutions
Solution 1: Dynamic Programming + Prefix Sum Optimization
Thinking
Split \(\textit{nums}[i]\) into \(\textit{arr1}[i]+\textit{arr2}[i]\) with \(\textit{arr1}\) non-decreasing and \(\textit{arr2}\) non-increasing. \(n\le 2000\) and \(\textit{nums}[i]\le 50\), so enumerating splits is exponential. The state is “up to \(i\) with \(\textit{arr1}[i]=j\)”.
Monotonicity of \(\textit{arr1}\) needs a previous \(j'\le j\); of \(\textit{arr2}\), \(j'\le j+\textit{nums}[i-1]-\textit{nums}[i]\). The feasible \(j'\) form a prefix, so a prefix sum of \(f[i-1]\) transfers in \(O(1)\). The answer is the sum of the last row.
We define \(f[i][j]\) to represent the number of monotonic array pairs for the subarray \([0, \ldots, i]\) where \(\textit{arr1}[i] = j\). Initially, \(f[i][j] = 0\), and the answer is \(\sum_{j=0}^{\textit{nums}[n-1]} f[n-1][j]\).
When \(i = 0\), we have \(f[0][j] = 1\) for \(0 \leq j \leq \textit{nums}[0]\).
When \(i > 0\), we can calculate \(f[i][j]\) based on \(f[i-1][j']\). Since \(\textit{arr1}\) is non-decreasing, \(j' \leq j\). Additionally, since \(\textit{arr2}\) is non-increasing, \(\textit{nums}[i] - j \leq \textit{nums}[i - 1] - j'\). Thus, \(j' \leq \min(j, j + \textit{nums}[i - 1] - \textit{nums}[i])\).
The answer is \(\sum_{j=0}^{\textit{nums}[n-1]} f[n-1][j]\).
The time complexity is \(O(nm)\), and the space complexity is \(O(nm)\), where \(n\) represents the length of the array \(\textit{nums}\), and \(m\) represents the maximum value in the array \(\textit{nums}\).