Suppose that every steak initially receives vinegar, giving a baseline score . Assigning A1 sauce to steak instead gains , while assigning salt gains .
Sort the steaks by decreasing . If an earlier steak receives salt while a later steak receives A1 sauce, swapping their sauces cannot decrease the total score. Thus there exists an optimal assignment in which every steak receiving A1 sauce occurs before every steak receiving salt.
Let be a split between these groups. Necessarily . Let be the sum of the largest gains among the first steaks, and let be the sum of the largest gains among the last steaks. The answer is
Compute all prefix values and suffix values using min-heaps of size , then check all possible split positions. This takes time and space. The magnitude of any answer is at most , so signed 64-bit integers suffice.
Solution written by GPT6