A prison has P cells in one row, numbered 1,2,…,P from the left. Every cell is a solitary cell and holds exactly one prisoner. Neighboring cells share a window, so a prisoner can talk to the prisoner next door.
When you release the prisoner of some cell, the prisoner in each cell right next to it learns about it and starts a riot. Releasing one prisoner therefore costs one gold coin for the prisoner in each of the two neighboring cells. The news keeps traveling sideways from window to window, so you have to pay every prisoner the news reaches. An empty cell has no prisoner to pass the news along, so the news stops there.
Today you release the Q prisoners held in cells A1,A2,…,AQ. The number of coins depends on the order of the releases. Find the order that spends the fewest coins and report how many coins that order needs.