New Year Chaos Challenge in HackerRank

According to HackerRank New Year Chaos Problem, i should understand that how many time each person in queue can bribe the person directly in front of them to swap positions.

I should print an integer denoting the minimum number of bribes needed to get the queue into its final state. Print ‘Too chaotic’ if the state is invalid.for example, it requires a person to have bribed more than people.

private static void NewYearChaosOperation(int[] arr)
{
var _countOfSwap = 0;
var _arrayLength = arr.Length - 1;
//1, 2, 5, 3, 4, 7, 8, 6
//firstly i want to make looping through complete array
for (int i = _arrayLength; i >= 0; i--)
{
//this condition check current element euqals
//with current position, so i can continue
//looping and there is no nedd to traversing
if (arr[i] == i + 1) { continue; }
//in step i check 'i' as a current position
//value with adjecent element
//so if my condition is valid, i need to one
//swap and one unit increse _countOfSwap
//variable
if ((i - 1) >= 0 && arr[i - 1] == i + 1)
{
_countOfSwap++;
Swap(arr, i, i - 1);
}
else
//and if my previus condition wasn't going to
//happen, i check 2 previus element with
//current position valueso if my condition
//is valid , i need to 2 swap and 2 unit
//increse _countOfSwap variable
if ((i - 2) >= 0 && arr[i - 2] == i + 1)
{
_countOfSwap += 2;
Swap(arr, i - 2, i - 1);
Swap(arr, i - 1, i);
}
else
//at the end accordig to problem statment if
//i have more than 2 bribes i should
//return 'Too chaotic'
{
Console.WriteLine("Too chaotic");
return;
}
}
Console.WriteLine(_countOfSwap);
}

I have a dream to have a spectacular garden

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store