File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 278527853535|[ Unit Conversion II] ( ./solutions/3535-unit-conversion-ii.js ) |Medium|
278627863539|[ Find Sum of Array Product of Magical Sequences] ( ./solutions/3539-find-sum-of-array-product-of-magical-sequences.js ) |Hard|
278727873541|[ 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|
278827893623|[ Count Number of Trapezoids I] ( ./solutions/3623-count-number-of-trapezoids-i.js ) |Medium|
27892790
27902791## License
Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments