hwangnk1004 / Algorithm

0 stars 0 forks source link

StepByStep #비토의 가족 #281

Open hwangnk1004 opened 4 years ago

hwangnk1004 commented 4 years ago

import java.util.Scanner;

public class Main { public static void main(String args[]) {

    Scanner scanner = new Scanner(System.in);

    int n =scanner.nextInt();

    int arr[] = new int[n];
    int count =0;
    for(int i=0; i<n; i++ ){
        arr[i]= scanner.nextInt();
    }
    for(int i=0 ;i<n-1; i++){
        for(int j=i+1; j<n; j++){
            if (arr[i] >arr[j]) {
                int empty = arr[i];
                arr[i] = arr[j];
                arr[j] = empty;
            }
        }
    }

    int sum = 0;
    if (n % 2 != 0) {
        for(int i=0; i<n/2; i++) {
            sum+= arr[n/2] - arr[i];
        }
        for(int i=n-1; i>n/2 ; i--) {
            sum+= arr[i] - arr[n/2];
        }

        System.out.println(sum);
    } else {
        for(int i=0; i<n/2-1; i++) {
            sum += arr[n/2-1] - arr[i];
        }
        for(int i=n-1; i>n/2-1; i--) {
            sum+= arr[i] - arr[n/2-1];
        }
        System.out.println(sum);

    }

}

}