You are viewing a single comment's thread. Return to all comments →
Counted the number of inversions for every element. Times out on 4 cases, how to improve it?
public static int calsum(int[] arr, int index){ int temp = arr[index]; int count = 0 ; for(int j=index+1 ; j<arr.length ; j++){ if(arr[j]<temp){ count++; } if(count>2){ count=-1; return -1; } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int a0 = 0; a0 < T; a0++){ int n = in.nextInt(); int q[] = new int[n]; for(int q_i=0; q_i < n; q_i++){ q[q_i] = in.nextInt(); } int sum = 0; int tsum = 0; for(int i =0; i<q.length; i++){ tsum = calsum(q,i); if(tsum==-1){ break; } else{ sum+=tsum; } } if(tsum==-1){ System.out.println("Too chaotic"); } else{ System.out.println(sum); } // your code goes here } }
Seems like cookies are disabled on this browser, please enable them to open this website
New Year Chaos
You are viewing a single comment's thread. Return to all comments →
Counted the number of inversions for every element. Times out on 4 cases, how to improve it?