public class ColorTheCells {
public int Dfs(int[] dryingTime, int[] paintTime, int pos = 0, int used = 0, int currentTime = 0) {
int n = dryingTime.Length;
if (used == (1 << n) - 1)
return currentTime;
int minTime = int.MaxValue;
for (int movePos = 0; movePos < n; movePos++) {
int dx = (pos <= movePos) ? 1 : -1;
int p = pos;
int time = currentTime;
while (p != movePos) {
time++;
int nx = p + dx;
if (((1 << nx) & used) != 0)
time = Math.Max(time, paintTime[nx] + dryingTime[nx] + 1);
p = nx;
}
foreach (var paintPos in new[] { movePos - 1, movePos + 1 }) {
if (0 <= paintPos && paintPos < n && ((1 << paintPos) & used) == 0) {
paintTime[paintPos] = time + 1;
minTime = Math.Min(minTime, Dfs(dryingTime, paintTime, movePos, used | (1 << paintPos), time + 1));
paintTime[paintPos] = 0;
}
}
}
return minTime;
}
public int minimalTime(int[] dryingTime) {
int[] paintTime = new int[dryingTime.Length];
return Dfs(dryingTime, paintTime);
}