Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 * 1041 <= nums[i] <= 1090 <= k <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Sliding Window · Monotonic Queue
[9,4,1,3,7] 4
[3,3,4] 0
number-of-great-partitions)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3578: Count Partitions With Max-Min Difference at Most K
class Solution {
public int countPartitions(int[] nums, int k) {
final int mod = (int) 1e9 + 7;
TreeMap<Integer, Integer> sl = new TreeMap<>();
int n = nums.length;
int[] f = new int[n + 1];
int[] g = new int[n + 1];
f[0] = 1;
g[0] = 1;
int l = 1;
for (int r = 1; r <= n; r++) {
int x = nums[r - 1];
sl.merge(x, 1, Integer::sum);
while (sl.lastKey() - sl.firstKey() > k) {
if (sl.merge(nums[l - 1], -1, Integer::sum) == 0) {
sl.remove(nums[l - 1]);
}
++l;
}
f[r] = (g[r - 1] - (l >= 2 ? g[l - 2] : 0) + mod) % mod;
g[r] = (g[r - 1] + f[r]) % mod;
}
return f[n];
}
}
// Accepted solution for LeetCode #3578: Count Partitions With Max-Min Difference at Most K
func countPartitions(nums []int, k int) int {
const mod int = 1e9 + 7
sl := redblacktree.New[int, int]()
merge := func(st *redblacktree.Tree[int, int], x, v int) {
c, _ := st.Get(x)
if c+v == 0 {
st.Remove(x)
} else {
st.Put(x, c+v)
}
}
n := len(nums)
f := make([]int, n+1)
g := make([]int, n+1)
f[0], g[0] = 1, 1
for l, r := 1, 1; r <= n; r++ {
merge(sl, nums[r-1], 1)
for sl.Right().Key-sl.Left().Key > k {
merge(sl, nums[l-1], -1)
l++
}
f[r] = g[r-1]
if l >= 2 {
f[r] = (f[r] - g[l-2] + mod) % mod
}
g[r] = (g[r-1] + f[r]) % mod
}
return f[n]
}
# Accepted solution for LeetCode #3578: Count Partitions With Max-Min Difference at Most K
class Solution:
def countPartitions(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
sl = SortedList()
n = len(nums)
f = [1] + [0] * n
g = [1] + [0] * n
l = 1
for r, x in enumerate(nums, 1):
sl.add(x)
while sl[-1] - sl[0] > k:
sl.remove(nums[l - 1])
l += 1
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]
// Accepted solution for LeetCode #3578: Count Partitions With Max-Min Difference at Most K
use std::collections::BTreeMap;
impl Solution {
pub fn count_partitions(nums: Vec<i32>, k: i32) -> i32 {
const mod_val: i32 = 1_000_000_007;
let n = nums.len();
let mut f = vec![0; n + 1];
let mut g = vec![0; n + 1];
f[0] = 1;
g[0] = 1;
let mut sl = BTreeMap::new();
let mut l = 1;
for r in 1..=n {
let x = nums[r - 1];
*sl.entry(x).or_insert(0) += 1;
while sl.keys().last().unwrap() - sl.keys().next().unwrap() > k {
let val = nums[l - 1];
if let Some(cnt) = sl.get_mut(&val) {
*cnt -= 1;
if *cnt == 0 {
sl.remove(&val);
}
}
l += 1;
}
f[r] = (g[r - 1] - if l >= 2 { g[l - 2] } else { 0 } + mod_val) % mod_val;
g[r] = (g[r - 1] + f[r]) % mod_val;
}
f[n]
}
}
// Accepted solution for LeetCode #3578: Count Partitions With Max-Min Difference at Most K
import { AvlTree } from 'datastructures-js';
function countPartitions(nums: number[], k: number): number {
const mod = 1_000_000_007;
const n = nums.length;
const cnt = new Map<number, number>();
const st = new AvlTree<number>((a, b) => a - b);
function insert(x: number) {
const c = (cnt.get(x) || 0) + 1;
cnt.set(x, c);
if (c === 1) {
st.insert(x);
}
}
function erase(x: number) {
const c = cnt.get(x)! - 1;
cnt.set(x, c);
if (c === 0) {
st.remove(x);
}
}
const f = Array(n + 1).fill(0);
const g = Array(n + 1).fill(0);
f[0] = 1;
g[0] = 1;
for (let l = 1, r = 1; r <= n; ++r) {
const x = nums[r - 1];
insert(x);
while (st.max()!.getValue() - st.min()!.getValue() > k) {
erase(nums[l - 1]);
l++;
}
f[r] = (g[r - 1] - (l >= 2 ? g[l - 2] : 0) + mod) % mod;
g[r] = (g[r - 1] + f[r]) % mod;
}
return f[n];
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.