Maximum Height by Stacking Cuboids LeetCode solution in Rust

1
impl Solution {
2
pub fn max_height(cuboids: Vec<Vec<i32>>) -> i32 {
3
use std::cmp::*;
4
let m = cuboids.len();
5

6
let mut cuboids = cuboids
7
.into_iter()
8
.map(|mut cub| {
9
cub.sort();
10
cub.reverse();
11
(cub[0], cub[1], cub[2])
12
})
13
.collect::<Vec<_>>();
14

15
cuboids.sort();
16
cuboids.sort_by(|(x1, y1, z1), (x2, y2, z2)| {
17
// -- prevent wrong formatting
18
if x1 < x2 && y1 < y2 && z1 < z2 {
19
Ordering::Greater
20
} else {
21
Ordering::Less
22
}
23
});
24

25
let mut ans = vec![(0, 0, 0); m];
26
// walk through every pair since n size is only 100 and try
27
// to maximize stack in each position
28
ans[0] = cuboids[0];
29
for (i, (x, y, z)) in cuboids.into_iter().skip(1).enumerate() {
30
for j in 0..=i {
31
let prev = ans[j];
32
if prev.1 >= y && prev.2 >= z {
33
ans[i + 1] = ans[i + 1].max((x + prev.0, y, z));
34
} else {
35
ans[i + 1] = ans[i + 1].max((x, y, z));
36
}
37
}
38
}
39

40
ans.into_iter().map(|(x, _, _)| x).max().unwrap()
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0