KatInterview

Minimum Cost to Combine All Elements

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapgreedypriority-queue

Last updated

Tests greedy algorithm design and min-heap operations to repeatedly merge pairs optimally.

You are given an array of positive integers. You must reduce the array to a single element by repeatedly performing this operation:

  1. Select any two elements from the array
  2. Remove both elements
  3. Add their sum back into the array
  4. Pay a cost equal to that sum

Return the minimum total cost required to reduce the array to one element.

If the array contains only one element, no operations are needed and the cost is zero.

Constraints

  • 1 ≤ array length ≤ 10⁵
  • 1 ≤ each element ≤ 10⁹
  • All elements are positive integers
  • The operation must be repeated until exactly one element remains

Examples

Example 1

Input: minimum_combination_cost([4, 3, 2, 6])

Output: 29

Example 2

Input: minimum_combination_cost([1, 2, 3, 4, 5])

Output: 33

Example 3

Input: minimum_combination_cost([10])

Output: 0

Example 4

Input: minimum_combination_cost([5, 5, 5, 5])

Output: 40

Hints

Hint 1

What data structure lets you efficiently find and extract the two smallest elements repeatedly?

Hint 2

Think about which pairs you should combine first. Does combining the largest elements early help or hurt?

Hint 3

Consider modeling the merges as a tree where leaves are original numbers and internal nodes are sums. How does the tree structure affect the total cost?