Skip to content

Commit 95f5f74

Browse files
authored
Create 0629-k-inverse-pairs-array.kt
1 parent 286bdbd commit 95f5f74

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

kotlin/0629-k-inverse-pairs-array.kt

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Bottom-up DP, Time O(n^2 * k) and Space O(n * k)
2+
class Solution {
3+
fun kInversePairs(n: Int, k: Int): Int {
4+
val mod = 1_000_000_007
5+
val dp = Array (n + 1) { LongArray (k + 1) }
6+
7+
dp[0][0] = 1
8+
for (i in 1..n) {
9+
for (j in 0..k) {
10+
for (p in 0 until i) {
11+
if (j - p >= 0)
12+
dp[i][j] = (dp[i][j] + dp[i - 1][j - p]) % mod
13+
}
14+
}
15+
}
16+
17+
return dp[n][k].toInt()
18+
}
19+
}
20+
21+
// Space optimized Bottom-up DP, Time O(n^2 * k) and Space O(k)
22+
class Solution {
23+
fun kInversePairs(n: Int, k: Int): Int {
24+
val mod = 1_000_000_007
25+
var dp = LongArray (k + 1)
26+
27+
dp[0] = 1
28+
for (i in 1..n) {
29+
val newDp = LongArray (k + 1)
30+
for (j in 0..k) {
31+
for (p in 0 until i) {
32+
if (j - p >= 0)
33+
newDp[j] = (newDp[j] + dp[j - p]) % mod
34+
}
35+
}
36+
dp = newDp
37+
}
38+
39+
return dp[k].toInt()
40+
}
41+
}
42+
43+
// Space optimized DP + Sliding window Time O(n * k) and Space O(k)
44+
class Solution {
45+
fun kInversePairs(n: Int, k: Int): Int {
46+
val mod = 1_000_000_007
47+
var prev = LongArray (k + 1)
48+
49+
prev[0] = 1
50+
for (i in 1..n) {
51+
val cur = LongArray (k + 1)
52+
var total = 0L
53+
for (j in 0..k) {
54+
if (j >= i)
55+
total -= prev[j - i]
56+
total = (total + prev[j] + mod) % mod
57+
cur[j] = total
58+
}
59+
prev = cur
60+
}
61+
62+
return prev[k].toInt()
63+
}
64+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy