Prove the greedy rule first
transcript
You pick a greedy rule for a contest problem. It sounds right: shortest report first. Does it hold?
Take two reports. A takes two minutes, with weight one. B takes three minutes, with weight nine. Put A first. The total is forty-seven. Put B first. The total is thirty-two.
The shorter report went first, and the total was higher. So the rule you picked is wrong. A quick test on two reports found it.
To find a safe rule, swap two neighbours in an order. Keep the order with the smaller total. The rule falls out of the algebra.
A first minus B first is fifteen. That is nine times two, minus one times three. Only these two products decide the order.
So sort by minutes divided by weight. A scores two. B scores one third. Lowest score goes first, so B wins.
In code, multiply instead of dividing. Keep the products and the total in sixty-four bits. Then stress test against a brute force.
Prove the rule before you code. Then test it against brute force. Full breakdown in the lecture.