Tuesday, May 12, 2020

Bribing problem - Java code

Problem


Solution

 // Complete the minimumBribes function below.
    static void minimumBribes(int[] q) {
        int bribes=0,sa=0;
        int[] smalArr=new int[q.length];
        boolean tooChaotic=false;
        for(int i=0;i<q.length;i++)
        { 
            int diff=(i+1)-q[i];
            if(diff<0)
            {
                bribes=bribes-diff;
                if(diff<-2) {tooChaotic=true;break;}
            }
            else if(i!=0 && i<=q.length-1)
            {
                smalArr[sa]=q[i];
                if(diff>1){
                for(int j=0;j<sa;j++)
                    if(q[i]<smalArr[j])
                        bribes++;
                }
                sa++;
            }
        }
        if(tooChaotic)
            System.out.println("Too chaotic");
        else
            System.out.println(bribes);
    }


No comments:

Post a Comment