private void GoBackAndFixStuff(int[] childrenScores, int childIndex, ChildrenCandies childrenCandies) { if (childIndex == 1) { childrenCandies.AddCandy(0, 1); return; } var currentChildCandies = childrenCandies.CandiesOf(childIndex); //Apply setting minimal candy prematurely for check below if (currentChildCandies == 0) { currentChildCandies = 1; } if (childrenCandies.CandiesOf(childIndex - 1) <= currentChildCandies) { childrenCandies.AddCandy(childIndex - 1, 1); } if (childrenScores[childIndex - 2] > childrenScores[childIndex - 1]) { GoBackAndFixStuff(childrenScores, childIndex - 1, childrenCandies); } }
public int HowManyCandiesToGive(int[] childrenScores, int childIndex, ChildrenCandies childrenCandies) { if (childIndex == 0 || childrenScores[childIndex - 1] == childrenScores[childIndex]) { return(1); } if (childrenScores[childIndex - 1] < childrenScores[childIndex]) { return(childrenCandies.CandiesOf(childIndex - 1) + 1); } else if (childrenScores[childIndex - 1] > childrenScores[childIndex]) { GoBackAndFixStuff(childrenScores, childIndex, childrenCandies); return(1); } throw new InvalidOperationException("This should be unreachable"); }
public long SolveCase(int[] childrenScores) { var childrenCandies = new ChildrenCandies(childrenScores.Length); if (ShouldReverse(childrenScores, 0.2)) { childrenScores = childrenScores.Reverse().ToArray(); } for (var i = 0; i < childrenScores.Length; i++) { if (i == 0) { childrenCandies.AddCandy(0, 1); continue; } childrenCandies.AddCandy(i, HowManyCandiesToGive(childrenScores, i, childrenCandies)); } return(childrenCandies.TotalCandies); }