Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Introduction to Greedy Algorithm

You are given pairs of numbers, where each pair [a, b] can be followed by another pair [c, d] only when b < c. Find the longest chain you can build.

[[1, 2], [7, 8], [2, 4], [4, 6]]   the longest chain is 3

Trying every arrangement is exact and far too slow. The number of orderings grows factorially, so it stops finishing at around ten pairs.

Now think about which pair should come first. Not the shortest one, and not the one starting earliest. The one that ends earliest, because it leaves the most room for everything after it.

Once you accept that, the rest follows

.....

.....

.....

Like the course? Get enrolled and start learning!