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 Valid Partitions: [4,6,1,2] with k=24612Test All Possible Partitions:[4,6,1,2]: max-min = 6-1 = 5 > 2 ✗[4,6]: diff=2≤2 ✓[1,2]: diff=1≤2 ✓[4]: ok[6,1,2]: diff=5>2 ✗Valid Partitions: 1
Understanding the Visualization
1
Input
Array [4,6,1,2] with constraint k=2
2
Check Partitions
Test all ways to split into contiguous segments
3
Count Valid
Count partitions where each segment has max-min ≤ k
Key Takeaway
🎯 Key Insight: Use dynamic programming to count valid partitions by trying all segments ending at each position
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