#2551

Put Marbles in Bags

Hard
ArrayGreedySortingHeap (Priority Queue)GreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach leverages the fact that only the endpoints of the bags matter for calculating scores. By focusing on the largest and smallest weights, we can maximize and minimize the score efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the weights array.
  2. 2Step 2: The minimum score is calculated using the first k smallest weights for the left endpoints and the last k smallest weights for the right endpoints.
  3. 3Step 3: The maximum score is calculated using the first k largest weights for the left endpoints and the last k largest weights for the right endpoints.
  4. 4Step 4: Return the difference between the maximum and minimum scores.
solution.py7 lines
1# Full working Python code
2
3def maxMinDifference(weights, k):
4    weights.sort()
5    min_score = sum(weights[i] + weights[-(i + 1)] for i in range(k))
6    max_score = sum(weights[-(i + 1)] + weights[i] for i in range(k))
7    return max_score - min_score

Complexity note: The complexity is dominated by the sorting step, which is O(n log n), while the subsequent calculations are linear, O(n).

  • 1Only the endpoints of the bags matter for calculating scores.
  • 2Sorting the weights allows us to easily access the smallest and largest weights.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.