Skip to content

Commit 4356df8

Browse files
committed
Add problem 2517: Maximum Tastiness of Candy Basket
1 parent 83851b2 commit 4356df8

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1877,6 +1877,7 @@ pub mod problem_2511_maximum_enemy_forts_that_can_be_captured;
18771877
pub mod problem_2512_reward_top_k_students;
18781878
pub mod problem_2515_shortest_distance_to_target_string_in_a_circular_array;
18791879
pub mod problem_2516_take_k_of_each_character_from_left_and_right;
1880+
pub mod problem_2517_maximum_tastiness_of_candy_basket;
18801881

18811882
#[cfg(test)]
18821883
mod test_utilities;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::iter::Copied;
6+
use std::slice::Iter;
7+
8+
impl Solution {
9+
fn check(first_price: u32, mut price_iter: Copied<Iter<u32>>, k: u32, candidate: u32) -> bool {
10+
let mut prev = first_price;
11+
12+
(1..k).all(|_| {
13+
let target = prev + candidate;
14+
15+
price_iter.find(|&value| value >= target).is_some_and(|next| {
16+
prev = next;
17+
18+
true
19+
})
20+
})
21+
}
22+
23+
pub fn maximum_tastiness(price: Vec<i32>, k: i32) -> i32 {
24+
let mut price = price.into_iter().map(|x| x as u32).collect::<Vec<_>>();
25+
let k = k as u32;
26+
27+
price.sort_unstable();
28+
29+
let mut iter = price.iter().copied();
30+
let first_price = iter.next().unwrap();
31+
let mut left = 0;
32+
let mut right = (price.last().unwrap() - first_price) / (k - 1) + 1;
33+
34+
while left < right {
35+
let middle = (left + right) / 2;
36+
37+
if Self::check(first_price, iter.clone(), k, middle) {
38+
left = middle + 1;
39+
} else {
40+
right = middle;
41+
}
42+
}
43+
44+
(left - 1) as _
45+
}
46+
}
47+
48+
// ------------------------------------------------------ snip ------------------------------------------------------ //
49+
50+
impl super::Solution for Solution {
51+
fn maximum_tastiness(price: Vec<i32>, k: i32) -> i32 {
52+
Self::maximum_tastiness(price, k)
53+
}
54+
}
55+
56+
#[cfg(test)]
57+
mod tests {
58+
#[test]
59+
fn test_solution() {
60+
super::super::tests::run::<super::Solution>();
61+
}
62+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod binary_search;
2+
3+
pub trait Solution {
4+
fn maximum_tastiness(price: Vec<i32>, k: i32) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
((&[13, 5, 1, 8, 21, 2] as &[_], 3), 8),
14+
((&[1, 3, 1], 2), 2),
15+
((&[7, 7, 7, 7], 2), 0),
16+
];
17+
18+
for ((price, k), expected) in test_cases {
19+
assert_eq!(S::maximum_tastiness(price.to_vec(), k), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)