Skip to content

Commit

Permalink
Add problem 2294: Partition Array Such That Maximum Difference Is K
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 25, 2024
1 parent d57ab30 commit 430b3ac
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1702,6 +1702,7 @@ pub mod problem_2285_maximum_total_importance_of_roads;
pub mod problem_2287_rearrange_characters_to_make_target_string;
pub mod problem_2288_apply_discount_to_prices;
pub mod problem_2293_min_max_game;
pub mod problem_2294_partition_array_such_that_maximum_difference_is_k;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn partition_array(nums: Vec<i32>, k: i32) -> i32 {
let mut nums = nums;

nums.sort_unstable();

let mut result = 1;
let mut iter = nums.iter().copied();
let mut last = iter.next().unwrap() + k;

for num in iter {
if num > last {
result += 1;
last = num + k;
}
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn partition_array(nums: Vec<i32>, k: i32) -> i32 {
Self::partition_array(nums, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod iterative;

pub trait Solution {
fn partition_array(nums: Vec<i32>, k: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
((&[3, 6, 1, 2, 5] as &[_], 2), 2),
((&[1, 2, 3], 1), 2),
((&[2, 2, 4, 5], 0), 3),
];

for ((nums, k), expected) in test_cases {
assert_eq!(S::partition_array(nums.to_vec(), k), expected);
}
}
}

0 comments on commit 430b3ac

Please sign in to comment.