2551. Put Marbles in Bags #1501
-
Topics: You have Divide the marbles into the k bags according to the following rules:
The score after distributing the marbles is the sum of the costs of all the Return the difference between the maximum and minimum scores among marble distributions. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the difference between the maximum and minimum possible scores when distributing marbles into k bags. Each bag must contain contiguous subarrays of marbles, and the score for each bag is the sum of the first and last marble's weight in that bag. Approach
Let's implement this solution in PHP: 2551. Put Marbles in Bags <?php
/**
* @param Integer[] $weights
* @param Integer $k
* @return Integer
*/
function putMarbles($weights, $k) {
$n = count($weights);
if ($k == 1) {
return 0;
}
$pairs = array();
for ($i = 0; $i < $n - 1; $i++) {
$pairs[] = $weights[$i] + $weights[$i + 1];
}
sort($pairs);
$m = $k - 1;
$min_sum = 0;
$max_sum = 0;
$pair_count = count($pairs);
for ($i = 0; $i < $m; $i++) {
$min_sum += $pairs[$i];
}
for ($i = $pair_count - 1; $i >= $pair_count - $m; $i--) {
$max_sum += $pairs[$i];
}
return $max_sum - $min_sum;
}
// Example test cases
$weights1 = [1, 3, 5, 1];
$k1 = 2;
echo putMarbles($weights1, $k1) . "\n"; // Output: 4
$weights2 = [1, 3];
$k2 = 2;
echo putMarbles($weights2, $k2) . "\n"; // Output: 0
?> Explanation:
This approach efficiently computes the required difference using sorting and summation, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to determine the difference between the maximum and minimum possible scores when distributing marbles into k bags. Each bag must contain contiguous subarrays of marbles, and the score for each bag is the sum of the first and last marble's weight in that bag.
Approach
Understanding the Problem Constraints: Each bag must be a contiguous subarray. The score for each bag is the sum of the first and last elements of the subarray. The goal is to find the difference between the maximum and minimum scores possible with k bags.
Key Insight: The score for each bag can be determined by the sum of the first and last elements of each subarray. When splitting the array into k contiguous sub…