-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 01-maximum-tastiness-of-candy-basket.rs
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
impl Solution { | ||
pub fn maximum_tastiness(mut price: Vec<i32>, k: i32) -> i32 { | ||
price.sort_unstable(); | ||
let (mut left, mut right) = (0, price[price.len() - 1] - price[0]); | ||
let can_x = |x| { | ||
let mut num = 1; | ||
let mut last = price[0]; | ||
for i in 1..price.len() { | ||
if price[i] - last >= x { | ||
num += 1; | ||
last = price[i]; | ||
} | ||
if num >= k { | ||
return true; | ||
} | ||
} | ||
num >= k | ||
}; | ||
while left < right { | ||
let mid = (left + right + 1) / 2; | ||
if can_x(mid) { | ||
left = mid; | ||
} else { | ||
right = mid - 1; | ||
} | ||
} | ||
left | ||
} | ||
} |