Skip to content

Commit dc674c3

Browse files
committed
Add solution #3578
1 parent 8eee07f commit dc674c3

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2785,6 +2785,7 @@
27852785
3535|[Unit Conversion II](./solutions/3535-unit-conversion-ii.js)|Medium|
27862786
3539|[Find Sum of Array Product of Magical Sequences](./solutions/3539-find-sum-of-array-product-of-magical-sequences.js)|Hard|
27872787
3541|[Find Most Frequent Vowel and Consonant](./solutions/3541-find-most-frequent-vowel-and-consonant.js)|Easy|
2788+
3578|[Count Partitions With Max-Min Difference at Most K](./solutions/3578-count-partitions-with-max-min-difference-at-most-k.js)|Medium|
27882789
3623|[Count Number of Trapezoids I](./solutions/3623-count-number-of-trapezoids-i.js)|Medium|
27892790

27902791
## License
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 3578. Count Partitions With Max-Min Difference at Most K
3+
* https://leetcode.com/problems/count-partitions-with-max-min-difference-at-most-k
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer k. Your task is to partition nums
7+
* into one or more non-empty contiguous segments such that in each segment, the difference
8+
* between its maximum and minimum elements is at most k.
9+
*
10+
* Return the total number of ways to partition nums under this condition.
11+
*
12+
* Since the answer may be too large, return it modulo 109 + 7.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @param {number} k
18+
* @return {number}
19+
*/
20+
var countPartitions = function(nums, k) {
21+
const MOD = 1e9 + 7;
22+
const n = nums.length;
23+
const dp = new Array(n + 1).fill(0);
24+
dp[0] = 1;
25+
26+
let sum = 1;
27+
const minQueue = [];
28+
const maxQueue = [];
29+
30+
for (let left = 0, right = 0; right < n; right++) {
31+
while (maxQueue.length && nums[right] > nums[maxQueue.at(-1)]) maxQueue.pop();
32+
maxQueue.push(right);
33+
34+
while (minQueue.length && nums[right] < nums[minQueue.at(-1)]) minQueue.pop();
35+
minQueue.push(right);
36+
37+
while (nums[maxQueue[0]] - nums[minQueue[0]] > k) {
38+
sum = (sum - dp[left++] + MOD) % MOD;
39+
if (minQueue[0] < left) minQueue.shift();
40+
if (maxQueue[0] < left) maxQueue.shift();
41+
}
42+
43+
dp[right + 1] = sum;
44+
sum = (sum + dp[right + 1]) % MOD;
45+
}
46+
47+
return dp[n];
48+
};

0 commit comments

Comments
 (0)