All topics
109

Merging the two smallest, over and over

Tier 1Locked

Where it runs

1. The problem

Until now the greedy algorithms chose in an order known in advance. Interval scheduling sorted the requests once by end time and then walked the list; the exchange argument showed that one sort was enough. Here the order keeps changing. You combine items, and each combination creates a new item that has to be compared with everything left. The two smallest values you need for the next step change after every move, so one sort at the start cannot give them to you.

The concrete task. You have several files of sizes [1, 2, 3, 4] to merge into one. You can merge only two files at a time, and a merge costs as much work as the two files weigh together. The merged file goes back into the set and may be merged again. You want the smallest total cost of all the merges that leave one file.

The order of the merges changes the total. Merge 1+2=3 (cost 3), then 3+3=6 (cost 6), then 4+6=10 (cost 10): total 19. If you always take the two biggest files, you get 4+3=7, 7+2=9, 9+1=10, total 7 + 9 + 10 = 26. The small files then end up inside big merges again and again, and the total grows.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Problems that keep taking the two smallest or two largest values, combine them and put the result back. A heap gives you both values in O(log n) each round. The lesson's exact task is Minimum Cost to Connect Sticks (1167), which is premium on LeetCode.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy