Skip to content

Commit

Permalink
Add problem 2073: Time Needed to Buy Tickets
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 7, 2024
1 parent f81de6c commit 9d4a0ab
Show file tree
Hide file tree
Showing 3 changed files with 57 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 @@ -1440,6 +1440,7 @@ pub mod problem_2063_vowels_of_all_substrings;
pub mod problem_2068_check_whether_two_strings_are_almost_equivalent;
pub mod problem_2069_walking_robot_simulation_ii;
pub mod problem_2070_most_beautiful_item_for_each_query;
pub mod problem_2073_time_needed_to_buy_tickets;
pub mod problem_2078_two_furthest_houses_with_different_colors;
pub mod problem_2085_count_common_words_with_one_occurrence;
pub mod problem_2089_find_target_indices_after_sorting_array;
Expand Down
18 changes: 18 additions & 0 deletions src/problem_2073_time_needed_to_buy_tickets/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod sliding_window;

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

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

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

for ((tickets, k), expected) in test_cases {
assert_eq!(S::time_required_to_buy(tickets.to_vec(), k), expected);
}
}
}
38 changes: 38 additions & 0 deletions src/problem_2073_time_needed_to_buy_tickets/sliding_window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

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

impl Solution {
pub fn time_required_to_buy(tickets: Vec<i32>, k: i32) -> i32 {
let k = k as u32 as usize;
let mut result = 0;
let target = tickets[k];
let (left, right) = tickets.split_at(k + 1);

for &num in left {
result += num.min(target);
}

for &num in right {
result += num.min(target - 1);
}

result
}
}

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

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 9d4a0ab

Please sign in to comment.