From ae5d86655552bc2efc44a9fd3df49b1cc1f9367b Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 25 Apr 2024 22:06:08 -0700 Subject: [PATCH] max number of k-sum pairs --- max_k_sum_pairs/Cargo.toml | 6 ++++++ max_k_sum_pairs/src/main.rs | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 max_k_sum_pairs/Cargo.toml create mode 100644 max_k_sum_pairs/src/main.rs diff --git a/max_k_sum_pairs/Cargo.toml b/max_k_sum_pairs/Cargo.toml new file mode 100644 index 0000000..41bdc5c --- /dev/null +++ b/max_k_sum_pairs/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "max_k_sum_pairs" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/max_k_sum_pairs/src/main.rs b/max_k_sum_pairs/src/main.rs new file mode 100644 index 0000000..c1db6c4 --- /dev/null +++ b/max_k_sum_pairs/src/main.rs @@ -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 +}