Help me in solving ARRHALVES problem

My issue

Can anyone please help me to how to approach to this problem . I got the solution but I want to please help me somebody in understanding the solution

My code

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t-->0){ 
		int n = sc.nextInt();
        int arr[] = new int[2*n];
        for(int i = 0; i<2*n; i++){
            arr[i] = sc.nextInt();
        }
        boolean val[] = new boolean[2*n];
        for(int i = 0; i<n; i++){
            if(arr[i]<=n) val[i] = true;
           
        }
        for(int i = n; i<2*n; i++){
            if(arr[i]>n) val[i] = true;
        }
        int i = 0;
        int j = n;
        long count = 0;
        while( j != 2*n && i != n){
            if(val[i]) i++;
            else if(val[j]) j++;
            else{
                //count += n-i-1;
                count += j-i;
                j++;
                i++;
            }
        }
        System.out.println(count);
		}
	}
}

Problem Link: Array Halves Practice Coding Problem