Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Year Chaos HackerRank Practise Problem - C# solution optimization [closed]

static void minimumBribes(int[] q)
{
    Int32 TotalCount = 0;
    bool blnSuccess = true;
    Int32[] size = Ordering(q);
    for (int intI = 0; intI < q.Length; intI++)
    {
        Int32 Tempvariable = 0;
        Int32 TooChaotic = 0;
        Int32 index = Index(size,q[intI]);
        do
        {
            if (q[intI] != size[intI])
            {
                Tempvariable = size[index];
                size[index] = size[index - 1];
                size[index - 1] = Tempvariable;
                index = index - 1;
                TooChaotic = TooChaotic + 1;
                if (TooChaotic > 2)
                {
                    break;
                }
                TotalCount = TotalCount + 1;
            }
        } while (q[intI] != size[intI]);
        if (TooChaotic > 2)
        {
            Console.WriteLine("Too chaotic");
            blnSuccess = false;
            break;
        }
    }
    if (blnSuccess)
    {
        Console.WriteLine(TotalCount);
    }
}

static int[] Ordering(int[] z)
{
    int[] r = new int[z.Length];
    r = z.OrderBy(x => x).ToArray();
    return r;
}
static int Index(int[] z,int integer)
{
    for (int intI = 0; intI < z.Length; intI++)
    {
        if(z[intI]== integer)
        {
            return intI;
        }
    }
    return 0;
}

This code is working fine, but its runtime is too long. I'm getting "Terminated due to timeout" in HackerRank. However, the solution is working fine on the local computer but it's taking more time. Problem Link:https://www.hackerrank.com/challenges/new-year-chaos/problem.

Sample Input

2 (the number of test cases)

5 (number of people in the queue)

2 1 5 3 4 (n space-separated integers describing the final state of the queue)

5 (number of people in the queue)

2 5 1 3 4 (n space-separated integers describing the final state of the queue).

It must print an integer representing the minimum number of bribes necessary, or Too chaotic if the line configuration is not possible.

Output 3

Too chaotic

Question:

How do I reduce its runtime? Presently, I am using an array.

like image 398
Ramakrishna Avatar asked Mar 19 '26 03:03

Ramakrishna


1 Answers

I've solved it a few weeks ago, this is my solution to the problem (100%)

static void minimumBribes(int[] q) {
    int bribe = 0;
    bool chaotic = false;
    int n = q.Length;
    for(int i = 0; i < n; i++)
    {
        if(q[i]-(i+1) > 2)
        {               
            chaotic = true;
            break;     
        }
        for (int j = Math.Max(0, q[i]-2); j < i; j++)
            if (q[j] > q[i]) 
                bribe++;
    }
    if(chaotic)
        Console.WriteLine("Too chaotic");
    else
        Console.WriteLine(bribe);
}

You don't need any other methods than the one provided by the challenge

like image 189
Gianlucca Avatar answered Mar 21 '26 16:03

Gianlucca