There always exists an optimal solution involving either \(0\) or more upward shifts or \(0\) or more downward shifts, followed by \(0\) or more car removals. It cannot be better to combine both upward and downward shifts, nor to perform car removals before the desired shifts are done. Assuming for the moment that the grid has no bottom and top edges (i.e. that every car has somewhere to move when a shift is performed), performing \(x\) upward shifts results in the contents of row \(K+x\) being moved into row \(K\), while performing \(x\) downward shifts similarly results in row \(K-x\) being moved into row \(K\). We'll refer to this row which would end up in row \(K\) as the *target row*. We can choose any target row \(i\) at the cost of \(|i-K|\) shift moves. \(i\) may even be chosen to be outside the regular grid (with such rows implicitly considered to contain no blocks) – so, possible relevant choices for \(i\) include all rows between \(0\) and \(R+1\), inclusive. For a given target row \(i\), after performing the necessary \(|i-K|\) shifts, we would also need to remove every car ultimately present in row \(K\), which may be independently determined per column \(j\). If \(G_{i,j} =\) "X", then row \(K\) will certainly end up with a car in column \(j\) (either that car originally from row \(i\), or another car blocking that one). Otherwise, if \(G_{i,j} =\) ".", then row \(K\) will end up with a car in column \(j\) if and only if there are more than \(K-1\) cars in cells \(G_{1..i,j}\) and/or more than \(R-K\) cars in cells \(G_{i..R,j}\). These observations can then be turned into a solution. We'll consider each column independently, iterating over its cells from top to bottom while maintaining how many cars are above/below the current cell in that column. This allows us to determine whether or not each column would contribute \(1\) car for each possible choice of target row \(i\). These values can then be added up per row \(i\) and added to \(|i-K|\) to find the best choice of target row. This process takes \(O(RC)\) time. It can also be observed that only target rows within \(C\) rows of row \(K\) need to be considered, as shifting to further target rows must take longer than sticking with a target row of \(K\) and removing all cars in it, though this insight does not help improve the time complexity of this solution. [See David Harmeyer (SecondThread)'s solution video here.](https://youtu.be/o9PqijKhax0)