2551. Put Marbles in Bags Hard

@problem@discussion
#Array#Greedy#Sorting#Heap (Priority Queue)



1/**
2 * [2551] Put Marbles in Bags
3 *
4 * You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the i^th marble. You are also given the integer k.
5 * Divide the marbles into the k bags according to the following rules:
6 * 
7 * 	No bag is empty.
8 * 	If the i^th marble and j^th marble are in a bag, then all marbles with an index between the i^th and j^th indices should also be in that same bag.
9 * 	If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j].
10 * 
11 * The score after distributing the marbles is the sum of the costs of all the k bags.
12 * Return the difference between the maximum and minimum scores among marble distributions.
13 *  
14 * <strong class="example">Example 1:
15 * 
16 * Input: weights = [1,3,5,1], k = 2
17 * Output: 4
18 * Explanation: 
19 * The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. 
20 * The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. 
21 * Thus, we return their difference 10 - 6 = 4.
22 * 
23 * <strong class="example">Example 2:
24 * 
25 * Input: weights = [1, 3], k = 2
26 * Output: 0
27 * Explanation: The only distribution possible is [1],[3]. 
28 * Since both the maximal and minimal score are the same, we return 0.
29 * 
30 *  
31 * Constraints:
32 * 
33 * 	1 <= k <= weights.length <= 10^5
34 * 	1 <= weights[i] <= 10^9
35 * 
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/put-marbles-in-bags/
40// discuss: https://leetcode.com/problems/put-marbles-in-bags/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45    pub fn put_marbles(weights: Vec<i32>, k: i32) -> i64 {
46        
47    }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_2551() {
58    }
59}
60


Back
© 2025 bowen.ge All Rights Reserved.