max number of k-sum pairs
This commit is contained in:
parent
cbce321637
commit
ae5d866555
2 changed files with 45 additions and 0 deletions
6
max_k_sum_pairs/Cargo.toml
Normal file
6
max_k_sum_pairs/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "max_k_sum_pairs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
39
max_k_sum_pairs/src/main.rs
Normal file
39
max_k_sum_pairs/src/main.rs
Normal file
|
@ -0,0 +1,39 @@
|
|||
fn main() {
|
||||
let mut nums = [1, 2, 3, 4];
|
||||
dbg!(foo(&mut nums, 5));
|
||||
let mut nums = [3, 1, 3, 4, 3];
|
||||
dbg!(foo(&mut nums, 6));
|
||||
}
|
||||
|
||||
fn foo(nums: &mut [i32], k: i32) -> i32 {
|
||||
let mut max = 0;
|
||||
nums.sort_unstable();
|
||||
|
||||
let mut left = 0;
|
||||
let mut right = nums.len() - 1;
|
||||
|
||||
while left < right {
|
||||
let lv = nums[left];
|
||||
let rv = nums[right];
|
||||
let sum = lv + rv;
|
||||
if sum < k {
|
||||
if lv < rv {
|
||||
left += 1;
|
||||
} else {
|
||||
right -= 1;
|
||||
}
|
||||
} else if sum > k {
|
||||
if rv > lv {
|
||||
right -= 1;
|
||||
} else {
|
||||
left += 1;
|
||||
}
|
||||
} else {
|
||||
max += 1;
|
||||
left += 1;
|
||||
right -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
max
|
||||
}
|
Loading…
Reference in a new issue