Find the Count of Monotonic Pairs I Problem
Description
LeetCode Problem 3250.
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. arr1is monotonically non-decreasing, in other words,arr1[0] <= arr1[1] <= ... <= arr1[n - 1].arr2is monotonically non-increasing, in other words,arr2[0] >= arr2[1] >= ... >= arr2[n - 1].arr1[i] + arr2[i] == nums[i]for all0 <= i <= n - 1.
Return the count of monotonic pairs.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [2,3,2]
Output: 4
Explanation:
The good pairs are:
1. ([0, 1, 1], [2, 2, 1])
2. ([0, 1, 2], [2, 2, 0])
3. ([0, 2, 2], [2, 1, 0])
4. ([1, 2, 2], [1, 1, 0])
Example 2:
Input: nums = [5,5,5,5]
Output: 126
Constraints:
1 <= n == nums.length <= 20001 <= nums[i] <= 50
Solution
Approach: Dynamic Programming + Prefix Sums
Only arr1 has to be chosen: arr2[i] = nums[i] - arr1[i] follows from it. Let f[i][j] be the number of valid ways to fill positions 0..i with arr1[i] = j.
For i = 0, every j in [0, nums[0]] works. For i > 0, the previous value j' must satisfy two conditions: j' <= j because arr1 does not decrease, and nums[i] - j <= nums[i-1] - j' because arr2 does not increase. Together these say j' <= min(j, j + nums[i-1] - nums[i]). So f[i][j] is a prefix sum of row i - 1 up to that bound, which we compute once per row. The answer is the sum of the last row over j in [0, nums[n-1]], modulo 10^9 + 7.
Complexity: O(n * m) time and O(n * m) space, where m is the largest value in nums.
from itertools import accumulate
class Solution:
def countOfPairs(self, nums: List[int]) -> int:
mod = 10**9 + 7
n, m = len(nums), max(nums)
f = [[0] * (m + 1) for _ in range(n)]
for j in range(nums[0] + 1):
f[0][j] = 1
for i in range(1, n):
s = list(accumulate(f[i - 1]))
for j in range(nums[i] + 1):
k = min(j, j + nums[i - 1] - nums[i])
if k >= 0:
f[i][j] = s[k] % mod
return sum(f[-1][: nums[-1] + 1]) % mod