|
| 1 | +// 2064. Minimized Maximum of Products Distributed to Any Store |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/ |
| 5 | +// |
| 6 | +// Tags: Array - Binary Search |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Use binary search to try the possible results and see if they work. |
| 11 | + /// |
| 12 | + /// Time complexity: O(log(max(q))*m) - We binary search the result, for each try, we |
| 13 | + /// iterate over all quantities spreading them between stores. |
| 14 | + /// Space complexity: O(1) - We use an outer while loop with three usize pointers and an |
| 15 | + /// inner iterator plus fold. |
| 16 | + /// |
| 17 | + /// Runtime 24 ms Beats 100% |
| 18 | + /// Memory 3.24 MB Beats 100% |
| 19 | + pub fn minimized_maximum(n: i32, quantities: Vec<i32>) -> i32 { |
| 20 | + let (mut left, mut right) = (1, *quantities.iter().max().unwrap()); |
| 21 | + let mut mid; |
| 22 | + while left < right { |
| 23 | + mid = (left + right) / 2; |
| 24 | + // How many buckets do we need to spread this quantity at this spread rate? |
| 25 | + if quantities |
| 26 | + .iter() |
| 27 | + .fold(0, |acc, x| acc + ((x + mid - 1) / mid)) |
| 28 | + > n |
| 29 | + { |
| 30 | + left = mid + 1; |
| 31 | + } else { |
| 32 | + right = mid; |
| 33 | + } |
| 34 | + } |
| 35 | + left as i32 |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +// Tests. |
| 40 | +fn main() { |
| 41 | + let tests = [ |
| 42 | + (6, vec![11, 6], 3), |
| 43 | + (7, vec![15, 10, 10], 5), |
| 44 | + (1, vec![100000], 100000), |
| 45 | + ]; |
| 46 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 47 | + let mut success = 0; |
| 48 | + for (i, t) in tests.iter().enumerate() { |
| 49 | + let res = Solution::minimized_maximum(t.0, t.1.clone()); |
| 50 | + if res == t.2 { |
| 51 | + success += 1; |
| 52 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 53 | + } else { |
| 54 | + println!( |
| 55 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 56 | + i, t.2, res |
| 57 | + ); |
| 58 | + } |
| 59 | + } |
| 60 | + println!(); |
| 61 | + if success == tests.len() { |
| 62 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 63 | + } else if success == 0 { |
| 64 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 65 | + } else { |
| 66 | + println!( |
| 67 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 68 | + tests.len() - success |
| 69 | + ) |
| 70 | + } |
| 71 | +} |
0 commit comments