LeetCode/rs/k-inverse-pairs-array.rs
Matej Focko 2c3f0e2255
rs: add «629. K Inverse Pairs Array»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-01-28 00:45:48 +01:00

26 lines
786 B
Rust

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
}
}