Skip to content

3835. Count Partitions With Max Min Difference At Most K

Array Dynamic Programming Queue Sliding Window Prefix Sum Monotonic Queue

Problem - Count Partitions With Max Min Difference At Most K

Medium

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 109 + 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 * 104
  • 1 <= nums[i] <= 109
  • 0 <= k <= 109

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def countPartitions(self, nums: List[int], k: int) -> int:
        srted_list = SortedList()
        n = len(nums)
        dp = [1] + [0] * n
        g = [1] + [0] * n
        left = 1
        mod = 10**9 + 7
        for right, num in enumerate(nums, 1):
            srted_list.add(num)
            while srted_list[-1] - srted_list[0] > k:
                srted_list.remove(nums[left - 1])
                left += 1
            dp[right] = (g[right - 1] - (g[left - 2] if left >= 2 else 0) + mod) % mod
            g[right] = (g[right - 1] + dp[right]) % mod

        return dp[-1]

Submission Stats:

  • Runtime: 1465 ms (14.12%)
  • Memory: 25.9 MB (51.76%)