Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 31, 2025 20:17
Show Gist options
  • Save tatsuyax25/5124181fa5dfae0e2f0286078ac68d95 to your computer and use it in GitHub Desktop.
Save tatsuyax25/5124181fa5dfae0e2f0286078ac68d95 to your computer and use it in GitHub Desktop.
You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. Divide the marbles into the k bags according to the following rules: No bag is empty. If the ith ma
/**
* Calculates the difference between the maximum and minimum scores
* of distributing marbles into k bags based on given rules.
*
* @param {number[]} weights - Array representing the weights of marbles.
* @param {number} k - Number of bags to divide the marbles into.
* @return {number} - Difference between the maximum and minimum scores.
*/
var putMarbles = function(weights, k) {
// If there's only one bag, no need to calculate; the difference is 0.
if (k === 1) {
return 0;
}
// Create an array to store the sum of weights for adjacent pairs of marbles.
const splits = [];
for (let i = 0; i < weights.length - 1; i++) {
splits.push(weights[i] + weights[i + 1]); // Sum weights[i] and weights[i + 1]
}
// Sort the adjacent pair sums in ascending order.
splits.sort((a, b) => a - b);
// Initialize variables to store the sums of the k-1 smallest and largest splits.
let minSum = 0; // Sum of the k-1 smallest adjacent pair sums.
let maxSum = 0; // Sum of the k-1 largest adjacent pair sums.
// Add the smallest k-1 sums to minSum.
for (let i = 0; i < k - 1; i++) {
minSum += splits[i];
}
// Add the largest k-1 sums to maxSum.
for (let i = 0; i < k - 1; i++) {
maxSum += splits[splits.length - 1 - i]; // Access the largest elements in splits.
}
// Return the difference between maxSum and minSum.
return maxSum - minSum;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment