File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 475
475
623|[ Add One Row to Tree] ( ./0623-add-one-row-to-tree.js ) |Medium|
476
476
624|[ Maximum Distance in Arrays] ( ./0624-maximum-distance-in-arrays.js ) |Medium|
477
477
628|[ Maximum Product of Three Numbers] ( ./0628-maximum-product-of-three-numbers.js ) |Easy|
478
+ 629|[ K Inverse Pairs Array] ( ./0629-k-inverse-pairs-array.js ) |Hard|
478
479
637|[ Average of Levels in Binary Tree] ( ./0637-average-of-levels-in-binary-tree.js ) |Easy|
479
480
643|[ Maximum Average Subarray I] ( ./0643-maximum-average-subarray-i.js ) |Easy|
480
481
645|[ Set Mismatch] ( ./0645-set-mismatch.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 629. K Inverse Pairs Array
3
+ * https://leetcode.com/problems/k-inverse-pairs-array/
4
+ * Difficulty: Hard
5
+ *
6
+ * For an integer array nums, an inverse pair is a pair of integers [i, j] where
7
+ * 0 <= i < j < nums.length and nums[i] > nums[j].
8
+ *
9
+ * Given two integers n and k, return the number of different arrays consisting of numbers from
10
+ * 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return
11
+ * it modulo 109 + 7.
12
+ */
13
+
14
+ /**
15
+ * @param {number } n
16
+ * @param {number } k
17
+ * @return {number }
18
+ */
19
+ var kInversePairs = function ( n , k ) {
20
+ const MOD = 1e9 + 7 ;
21
+ const dp = new Array ( k + 1 ) . fill ( 0 ) ;
22
+
23
+ dp [ 0 ] = 1 ;
24
+ for ( let i = 1 ; i <= n ; i ++ ) {
25
+ const previous = dp . slice ( ) ;
26
+ dp [ 0 ] = 1 ;
27
+ for ( let j = 1 ; j <= k ; j ++ ) {
28
+ dp [ j ] = ( previous [ j ] + dp [ j - 1 ] ) % MOD ;
29
+ if ( j >= i ) dp [ j ] = ( dp [ j ] - previous [ j - i ] + MOD ) % MOD ;
30
+ }
31
+ }
32
+
33
+ return dp [ k ] ;
34
+ } ;
You can’t perform that action at this time.
0 commit comments