Greedy Algorithms8 sections · 316 units
Open in Course

Create Maximum - Merge Step

Lexicographic comparison

To merge two arrays into the lexicographically largest result:

At each step, compare the remaining suffixes. Pick from whichever array has the larger suffix.

function merge(a, b)
 result := []
 i := 0
 j := 0
 while i < len(a) or j < len(b)
 if suffix a[i:] > suffix b[j:] then
 result.append(a[i])
 i := i + 1
 else
 result.append(b[j])
 j := j + 1
 return result

Compare suffixes, not just current elements. [6,7][6,7] beats [6,3][6,3] even though both start with 66.