Count Partitions With Max-Min Difference at Most K - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,6,1,2], k = 2
Output: 1
💡 Note: Only one valid partition: [4,6] | [1,2]. First segment has max-min = 6-4 = 2 ≤ 2. Second segment has max-min = 2-1 = 1 ≤ 2.
Example 2 — Multiple Partitions
$ Input: nums = [1,3,1], k = 2
Output: 2
💡 Note: Two valid partitions: [1,3,1] (max-min = 3-1 = 2 ≤ 2) or [1,3] | [1] (first: 3-1=2≤2, second: 1-1=0≤2).
Example 3 — Single Element
$ Input: nums = [5], k = 1
Output: 1
💡 Note: Only one element, so only one partition [5] with max-min = 5-5 = 0 ≤ 1.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 105
  • 0 ≤ k ≤ 105

Visualization

Tap to expand
Count Partitions With Max-Min Difference at Most K INPUT Array nums: 4 i=0 6 i=1 1 i=2 2 i=3 k = 2 Constraint: In each segment max - min <= k Valid segment example: [4,6]: max=6, min=4 6-4=2 <= k=2 OK Invalid segment: [4,6,1]: 6-1=5 > 2 ALGORITHM STEPS 1 Initialize DP dp[i] = ways to partition nums[0..i], dp[0]=1 2 Track Min/Max Use monotonic deques for sliding window 3 DP Transition dp[i] = sum of dp[j] where max-min <= k 4 Return Answer dp[n] mod 10^9+7 DP Table: dp[0] dp[1] dp[2] dp[3] dp[4] 1 1 0 0 1 Only valid: [4,6] | [1,2] Both have diff <= 2 FINAL RESULT Output: 1 Valid Partition: [4, 6] | [1, 2] Verification: [4,6]: 6-4=2 2 <= 2 OK [1,2]: 2-1=1 1 <= 2 OK Why only 1 way? No other split satisfies max-min <= k for all segments simultaneously Key Insight: Use optimized DP with monotonic deques to efficiently track min/max in sliding windows. For each position i, find all valid starting positions j where segment [j..i] has max-min <= k. Prefix sum optimization reduces time complexity from O(n^2) to O(n) for summing dp values. TutorialsPoint - Count Partitions With Max-Min Difference at Most K | Optimized DP with Efficient Min/Max
Asked in
Google 25 Amazon 20 Microsoft 15
12.0K Views
Medium Frequency
~25 min Avg. Time
450 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