0

JAVA

while determining the minimum number of operations to make all the same in array and the condition is in one operation only any one element is removed. this code is showing the indexOutOfBounds error

    Scanner sc=new Scanner(System.in);
    int test=sc.nextInt();
    while(test>0){
        int n=sc.nextInt();
        int[] arr=new int[n];
        List<Integer>list=new ArrayList<Integer>(n);
        for(int i=0;i<n;i++){
            arr[i]=sc.nextInt();
        }
      for(int i=0;i<n;i++){
          list.add(arr[i]);
      }
        for(int i=0;i<n;i++){
            arr[arr[i]%n]+=n;
        }
        int max=-1;
        int res=0;
        for(int i=0;i<n;i++){
            if(arr[i]>max){
                max=arr[i];
                res=i;
            }
        }
        int count=0;
        for(int i=0;i<n;i++){
            if((list.get(i))!=(list.get(res))){
                list.remove(i);
                count++;
            }
        }
        System.out.println(count);
        test--;
    }
  • Please paste the complete stacktrace, and if you can put a marking comment in the line inside your code where the error originates. – hc_dev Sep 28 '22 at 17:17
  • You also don't post what your input was, you have user input and we have no idea what the expected input/output _should_ be – Nexevis Sep 28 '22 at 17:20
  • 1
    I bet `list.remove(i);` is the issue at a glance, you are removing from the `List` of size `n` while iterating to `n` in that same loop. – Nexevis Sep 28 '22 at 17:24

0 Answers0