-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnect_sticks.rs
37 lines (30 loc) · 914 Bytes
/
connect_sticks.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::collections::BinaryHeap;
// 1167. Minimum Cost to Connect Sticks, Medium
// https://leetcode.com/problems/minimum-cost-to-connect-sticks/
impl Solution {
pub fn connect_sticks(sticks: Vec<i32>) -> i32 {
let sticks = sticks.iter().map(|x| -x).collect::<Vec<i32>>();
let mut sticks_heap = BinaryHeap::from(sticks);
let mut cost = 0;
while sticks_heap.len() > 1 {
let stick = sticks_heap.pop().unwrap() + sticks_heap.pop().unwrap();
sticks_heap.push(stick);
cost += -stick;
}
cost
}
}
struct Solution {}
#[cfg(test)]
mod tests {
use super::*;
use crate::vec_vec_i32;
#[test]
fn test_connect_sticks() {
assert_eq!(Solution::connect_sticks(vec![2, 4, 3]), 14);
}
#[test]
fn test_connect_sticks2() {
assert_eq!(Solution::connect_sticks(vec![1, 8, 3, 5]), 30);
}
}