βœ…Arranging Students (Contest)

Arranging Students easy Time Limit: 2 sec Memory Limit: 128000 kB

Problem Statement :

In the morning assembly, there are N students standing in a line, such that the ith student from the front has height H[i].

In one move, you can pick any two students and swap their positions.

If you are allowed to do only one swap, can you arrange the students in increasing order of their hieghts? Input The first line of input contains T, the number of test cases. The first line of each test case contains N, the number of students in the line. The second line of each test case contains the heights of N students, where the ith index is the height of ith student.

Constraints: 1 <= T <= 103 1 <= N <= 104 1 <= H_i <= 105 Output For each test case, output YES or NO Example Sample Input 2 3 1 2 3 4 2 1 4 3

Sample Output YES NO

Explanation: The students are already standing in increasing order in the first test case, hence the answer is YES.

link:https://my.newtonschool.co/playground/code/2kycyl67ww93/

import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    public static void main (String[] args) {
        // Your code here
        Scanner sc= new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0){
            int n=sc.nextInt();
            int arr[]= new int[n];
            for(int i=0;i<n;i++){
                arr[i]=sc.nextInt();
            }
            int b[]=new int[n];
            for(int i=0;i<n;i++){
                b[i]=arr[i];
            }
            Arrays.sort(b,0,n);
            int ct=0;
            for(int i=0;i<n;i++){
                if(arr[i]!=b[i])
                ct++;
            }
            if(ct==0||ct==2){
                System.out.println("YES");
            }
            else{
                System.out.println("NO");
            }
        }
    }
}

Last updated