Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 009c5d7

Browse files
solve: 2551. Put Marbles in Bags in rust
Signed-off-by: rajput-hemant <rajput.hemant2001@gmail.com>
1 parent 5bff8f4 commit 009c5d7

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /