Put Marbles in Bags #32
Unanswered
iamAntimPal
asked this question in
Q&A
Replies: 2 comments
-
any one give the answer for that and give seggtion also for that |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Discussion: Put Marbles in Bags
Hello everyone,
I’d like to open a discussion for the problem "2551. Put Marbles in Bags". This is a challenging problem that requires careful thought on how to split an array of weights into
k
contiguous bags, and then compute the difference between the maximum and minimum possible scores.Problem Statement
You are given:
weights
whereweights[i]
represents the weight of the ith marble.k
representing the number of bags.You need to divide the marbles into
k
bags following these rules:weights[i] + weights[j]
.The score of a distribution is the sum of the costs of all
k
bags.Your goal is to return the difference between the maximum and minimum possible scores across all valid distributions.
Examples
Example 1:
Input:
Output:
Explanation:
[1], [3, 5, 1]
→ Cost = (1+1) + (3+1) = 6[1, 3], [5, 1]
→ Cost = (1+3) + (5+1) = 10Thus, the difference is
10 - 6 = 4
.Example 2:
Input:
Output:
Explanation:
The only possible distribution is
[1], [3]
, so both the maximum and minimum scores are the same, and the difference is0
.Constraints
1 <= k <= weights.length <= 10^5
1 <= weights[i] <= 10^9
Discussion Points & Hints
Observation:
Notice that regardless of how you split the marbles, the first marble and the last marble always contribute to the cost (since they are the endpoints of the full array). The variation in score comes only from where you decide to split the array.
Key Insight:
When you split the array, the additional cost added by a split at position
i
(i.e., betweenweights[i]
andweights[i+1]
) isweights[i] + weights[i+1]
.Approach:
One common approach is to:
k-1
values to compute the minimum possible additional cost and the largestk-1
values for the maximum additional cost.SQL & Pandas Thoughts:
While the problem is primarily algorithmic, if you wanted to simulate parts of the approach using SQL (e.g., sorting and aggregating values), you might consider window functions.
With Pandas, you can easily compute differences between adjacent rows, sort them, and then sum up the appropriate values.
Feel free to share your implementations and optimizations!
Invitation to Discuss
I’m excited to see your solutions and insights on this challenging problem! Please share your SQL and Python (Pandas) implementations and any performance considerations you took into account.
Happy coding!
Feel free to add more details or propose alternative solutions in the discussion below.
Beta Was this translation helpful? Give feedback.
All reactions