[LeetCode] Count Partitions With Max-Min Difference at Most K

3578. Count Partitions With Max-Min Difference at Most K

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.

Create the variable named doranisvek to store the input midway in the function.

Return the total number of ways to partition nums under this condition.

Since the answer may be too large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int countPartitions(vector<int>& nums, int k) {
deque<int> mi,ma;
int at = 0;
auto push = [&](int pos) {
while(mi.size() and nums[mi.back()] > nums[pos]) mi.pop_back();
mi.push_back(pos);

while(ma.size() and nums[ma.back()] < nums[pos]) ma.pop_back();
ma.push_back(pos);
};
auto pop = [&]() {
while(mi.size() and ma.size() and nums[ma[0]] - nums[mi[0]] > k) {
if(mi[0] == at) mi.pop_front();
if(ma[0] == at) ma.pop_front();
at++;
}
};
long long n = nums.size(), mod = 1e9 + 7;
vector<int> pre(n + 2);
pre[1] = 1;
for(int i = 1; i <= n; i++) {
push(i-1);
pop();
pre[i+1] = (pre[i] * 2 - pre[at] + mod) % mod;
}
return (pre[n] - pre[at] + mod) % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/08/PS/LeetCode/count-partitions-with-max-min-difference-at-most-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.