Count Partitions With Max-Min Difference at Most K Problem
Description
LeetCode Problem 3578.
You are given an integer array nums and an integer k. Your task is to partition nums into one or more non-empty contiguous segments such that in each segment, the difference between its maximum and minimum elements is at most k.
Return the total number of ways to partition nums under this condition.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [9,4,1,3,7], k = 4
Output: 6
Explanation:
There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most k = 4:
- [[9], [4], [1], [3], [7]]
- [[9], [4], [1], [3, 7]]
- [[9], [4], [1, 3], [7]]
- [[9], [4, 1], [3], [7]]
- [[9], [4, 1], [3, 7]]
- [[9], [4, 1, 3], [7]]
Example 2:
Input: nums = [3,3,4], k = 0
Output: 2
Explanation:
There are 2 valid partitions that satisfy the given conditions:
- [[3], [3], [4]]
- [[3, 3], [4]]
Constraints:
2 <= nums.length <= 5 * 10^41 <= nums[i] <= 10^90 <= k <= 10^9
Solution
Approach: DP with a Sliding Window
Let f[i] be the number of ways to partition the first i elements, with f[0] = 1. A segment is allowed when its maximum minus its minimum is at most k. If a segment is allowed, so is every sub-segment, so for each right end r the allowed left ends form an interval [l, r] that only moves right as r grows.
Maintain the window [l, r] with two monotonic deques (one for the maximum, one for the minimum) and move l forward while the difference exceeds k. Then f[r] = f[l - 1] + f[l] + ... + f[r - 1], which a prefix-sum array g (where g[i] = f[0] + ... + f[i]) answers in O(1).
The answer is f[n] modulo 10^9 + 7.
Complexity: O(n) time and O(n) space.
from collections import deque
class Solution:
def countPartitions(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
n = len(nums)
f = [1] + [0] * n
g = [1] + [0] * n
max_q = deque() # indices, values decreasing
min_q = deque() # indices, values increasing
l = 1
for r, x in enumerate(nums, 1):
while max_q and nums[max_q[-1] - 1] <= x:
max_q.pop()
max_q.append(r)
while min_q and nums[min_q[-1] - 1] >= x:
min_q.pop()
min_q.append(r)
while nums[max_q[0] - 1] - nums[min_q[0] - 1] > k:
l += 1
if max_q[0] < l:
max_q.popleft()
if min_q[0] < l:
min_q.popleft()
f[r] = (g[r - 1] - (g[l - 2] if l >= 2 else 0) + mod) % mod
g[r] = (g[r - 1] + f[r]) % mod
return f[n]