Skip to content

Commit 9282ce9

Browse files
authored
Create 2551. Put Marbles in Bags (#757)
2 parents 0165b7f + 65946fc commit 9282ce9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: 2551. Put Marbles in Bags

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
long long putMarbles(vector<int>& weights, int k) {
4+
int n=weights.size();
5+
vector<int> auxi; // create some Helping vector that store sum of pair.
6+
7+
// Compute the sum of adjacent pairs
8+
for(int i=0;i<n-1;i++){
9+
auxi.push_back(weights[i] + weights[i+1]);
10+
}
11+
12+
// Sort the pairs
13+
sort(auxi.begin(), auxi.end());
14+
long long minm=0,maxm=0;
15+
16+
// Select (k - 1) smallest sums for minSum
17+
for(int i=0;i<k-1;i++){
18+
minm = minm + auxi[i];
19+
}
20+
21+
// Select (k - 1) largest sums for maxSum
22+
for(int i=n-2;i>=n-k;i--){
23+
maxm= maxm+ auxi[i];
24+
}
25+
return maxm-minm;
26+
}
27+
};

0 commit comments

Comments
 (0)