1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00

rs: add «629. K Inverse Pairs Array»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-28 00:45:48 +01:00
parent 5a4efd75db
commit 2c3f0e2255
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,26 @@
impl Solution {
pub fn k_inverse_pairs(n: i32, k: i32) -> i32 {
let MOD = 1000000007;
let idx = |i, j| (i * (k + 1) + j) as usize;
let get = |dp: &[i32], i: i32, j: i32| {
if i < 0 || i > n || j < 0 || j > k {
return 0;
}
dp[idx(i, j)]
};
let mut dp = vec![0; ((n + 1) * (k + 1)) as usize];
for (i, j) in (1..=n).flat_map(|i| (0..=k).map(move |j| (i, j))) {
if j == 0 {
dp[idx(i, j)] = 1;
} else {
let val = (get(&dp, i - 1, j) + MOD - get(&dp, i - 1, j - i)) % MOD;
dp[idx(i, j)] = (get(&dp, i, j - 1) + val) % MOD;
}
}
(dp[idx(n, k)] + MOD - get(&dp, n, k - 1)) % MOD
}
}