25/28
Part 6 of 6 · Follow-upsLearn and do

What if you must fill as many slots as you can?

Back to the grid rule's fill-first choice. Trying every order works for 8 titles. For 30 it's hopeless: 30 titles in 30 slots is about 2.65 × 10³² orders.

The problem underneath is a matching. Titles on one side, slots on the other, a line wherever a title may sit in a slot. You want the most lines with no title and no slot used twice. That is maximum bipartite matching, and an augmenting path solves it:

  1. Give slot j a title that is free and allowed.
  2. If every allowed title is taken, pick one, say T in slot k, and try to give slot k a different title, by the same rule.
  3. If that works, slot k moves, and T goes to slot j.
Row A, B, C, with column 1 holding C and column 2 holding B and C
greedy
012rowAB
augmenting path
012rowCBA

Slot 2 can only take A. A is in slot 0, and slot 0 can take C instead, so A moves to slot 2.

Each slot's search visits each title at most once, so this costs O(width × titles × checks), polynomial instead of factorial. A tried set per search stops it from going around in a circle.

This fills the most slots, but not always from slot 0 with no gap. If the screen can't have a gap, ask the matching whether slots 0 to k - 1 can all be filled, for the largest k. And either way the row's order is no longer the ranking's order. That is the trade to state.

In the editor, write max_slots(row, width, columns): the most slots, any of them, that different titles of the row can fill under the grid rule.