We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5bff8f4 commit 009c5d7Copy full SHA for 009c5d7
src/2501-2600/2551 - Put Marbles in Bags/put_marbels_in_bag.rs
@@ -0,0 +1,15 @@
1
+impl Solution {
2
+ pub fn put_marbles(weights: Vec<i32>, k: i32) -> i64 {
3
+ let n = weights.len();
4
+ // pair weights of adjacent bags
5
+ let mut pair_weights: Vec<_> = (0..n - 1).map(|i| weights[i] + weights[i + 1]).collect();
6
+
7
+ // sort the pair weights
8
+ pair_weights.sort();
9
10
+ // sum the difference between the largest and smallest pair weights
11
+ (0..(k - 1) as usize).fold(0_i64, |ans, i| {
12
+ ans + (pair_weights[n - 2 - i] - pair_weights[i]) as i64
13
+ })
14
+ }
15
+}
0 commit comments