File tree Expand file tree Collapse file tree 2 files changed +19
-1
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 2 files changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -38,6 +38,7 @@ Your ideas/fixes/algorithms are more than welcome!
3838|632|[ Smallest Range] ( https://leetcode.com/problems/smallest-range/ ) |[ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_632.java ) | O(n* logk) |O(k) | Hard| Heap
3939|631|[ Design Excel Sum Formula] ( https://leetcode.com/problems/design-excel-sum-formula/ ) |[ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_631.java ) | | | Hard| Design, Topological Sort
4040|630|[ Course Schedule III] ( https://leetcode.com/problems/course-schedule-iii/ ) |[ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_630.java ) | O(n* logn) |O(n) | Hard| Heap, Greedy
41+ |629|[ K Inverse Pairs Array] ( https://leetcode.com/problems/k-inverse-pairs-array/ ) |[ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_629.java ) | O(n* k) |O(n* k) | Hard| DP
4142| 628| [ Maximum Product of Three Numbers] ( https://leetcode.com/problems/maximum-product-of-three-numbers/ ) | [ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_628.java ) | O(nlogn) | O(1) | Easy |
4243| 625| [ Minimum Factorization] ( https://leetcode.com/problems/minimum-factorization/ ) | [ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_625.java ) | O(?) | O(?) | Medium |
4344|624|[ Maximum Distance in Arrays] ( https://leetcode.com/problems/maximum-distance-in-arrays/ ) |[ Solution] ( ../master/src/main/java/com/fishercoder/solutions/_624.java ) | O(nlogn) |O(1) | Easy | Sort, Array
Original file line number Diff line number Diff line change 2525 */
2626public class _629 {
2727
28+ /**reference: https://leetcode.com/articles/k-inverse-pairs-array/#approach-5-another-optimized-dynamic-programming-approachaccepted
29+ * and
30+ * https://discuss.leetcode.com/topic/93815/java-dp-o-nk-solution*/
2831 public int kInversePairs (int n , int k ) {
29- return 0 ;
32+ int mod = 1000000007 ;
33+ if (k > n *(n -1 )/2 || k < 0 ) return 0 ;
34+ if (k == 0 || k == n *(n -1 )/2 ) return 1 ;
35+ long [][] dp = new long [n +1 ][k +1 ];
36+ dp [2 ][0 ] = 1 ;
37+ dp [2 ][1 ] = 1 ;
38+ for (int i = 3 ; i <= n ; i ++) {
39+ dp [i ][0 ] = 1 ;
40+ for (int j = 1 ; j <= Math .min (k , i *(i -1 )/2 ); j ++) {
41+ dp [i ][j ] = dp [i ][j -1 ] + dp [i -1 ][j ];
42+ if (j >= i ) dp [i ][j ] -= dp [i -1 ][j -i ];
43+ dp [i ][j ] = (dp [i ][j ]+mod ) % mod ;
44+ }
45+ }
46+ return (int ) dp [n ][k ];
3047 }
3148}
You can’t perform that action at this time.
0 commit comments