Skip to content

Commit

Permalink
Add problem 2412: Minimum Money Required Before Transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 27, 2025
1 parent 1fa4951 commit 95766a9
Show file tree
Hide file tree
Showing 3 changed files with 61 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 @@ -1796,6 +1796,7 @@ pub mod problem_2406_divide_intervals_into_minimum_number_of_groups;
pub mod problem_2409_count_days_spent_together;
pub mod problem_2410_maximum_matching_of_players_with_trainers;
pub mod problem_2411_smallest_subarrays_with_maximum_bitwise_or;
pub mod problem_2412_minimum_money_required_before_transactions;

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

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

impl Solution {
pub fn minimum_money(transactions: Vec<Vec<i32>>) -> i64 {
let mut max_diff = 0;
let mut diff_sum = 0;

for transaction in transactions {
let [cost, cashback] = <[_; 2]>::map(transaction.try_into().ok().unwrap(), |x| x as u32);

let min_diff = if cashback < cost {
diff_sum += u64::from(cost - cashback);

cashback
} else {
cost
};

max_diff = max_diff.max(min_diff);
}

(diff_sum + u64::from(max_diff)) as _
}
}

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

impl super::Solution for Solution {
fn minimum_money(transactions: Vec<Vec<i32>>) -> i64 {
Self::minimum_money(transactions)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2412_minimum_money_required_before_transactions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod greedy;

pub trait Solution {
fn minimum_money(transactions: Vec<Vec<i32>>) -> i64;
}

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

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

for (transactions, expected) in test_cases {
assert_eq!(S::minimum_money(transactions.iter().map(Vec::from).collect()), expected);
}
}
}

0 comments on commit 95766a9

Please sign in to comment.