Skip to content

Commit c98d8e7

Browse files
committed
Add solution #2551
1 parent 2ed2bab commit c98d8e7

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,080 LeetCode solutions in JavaScript
1+
# 1,081 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -1011,6 +1011,7 @@
10111011
2529|[Maximum Count of Positive Integer and Negative Integer](./solutions/2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
10121012
2535|[Difference Between Element Sum and Digit Sum of an Array](./solutions/2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
10131013
2542|[Maximum Subsequence Score](./solutions/2542-maximum-subsequence-score.js)|Medium|
1014+
2551|[Put Marbles in Bags](./solutions/2551-put-marbles-in-bags.js)|Hard|
10141015
2559|[Count Vowel Strings in Ranges](./solutions/2559-count-vowel-strings-in-ranges.js)|Medium|
10151016
2560|[House Robber IV](./solutions/2560-house-robber-iv.js)|Medium|
10161017
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|

solutions/2551-put-marbles-in-bags.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 2551. Put Marbles in Bags
3+
* https://leetcode.com/problems/put-marbles-in-bags/
4+
* Difficulty: Hard
5+
*
6+
* You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight
7+
* of the ith marble. You are also given the integer k.
8+
*
9+
* Divide the marbles into the k bags according to the following rules:
10+
* - No bag is empty.
11+
* - If the ith marble and jth marble are in a bag, then all marbles with an index between the ith
12+
* and jth indices should also be in that same bag.
13+
* - If a bag consists of all the marbles with an index from i to j inclusively, then the cost of
14+
* the bag is weights[i] + weights[j].
15+
*
16+
* The score after distributing the marbles is the sum of the costs of all the k bags.
17+
*
18+
* Return the difference between the maximum and minimum scores among marble distributions.
19+
*/
20+
21+
/**
22+
* @param {number[]} weights
23+
* @param {number} k
24+
* @return {number}
25+
*/
26+
var putMarbles = function(weights, k) {
27+
const n = weights.length;
28+
if (k === n) return 0;
29+
30+
const pairSums = [];
31+
for (let i = 0; i < n - 1; i++) {
32+
pairSums.push(weights[i] + weights[i + 1]);
33+
}
34+
35+
pairSums.sort((a, b) => a - b);
36+
37+
let minScore = 0;
38+
let maxScore = 0;
39+
40+
for (let i = 0; i < k - 1; i++) {
41+
minScore += pairSums[i];
42+
maxScore += pairSums[n - 2 - i];
43+
}
44+
45+
return maxScore - minScore;
46+
};

0 commit comments

Comments
 (0)