[백준/BOJ] 27277. 장기자랑 [Silver 1]

jychan99·2023년 9월 20일
0

  1. 장기자랑
    문제출처 : https://www.acmicpc.net/problem/27277
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main{
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;
    static int N,result=0;
    static ArrayList<Integer> list =new ArrayList<>();
    static int[] asc,desc;

    public static void main(String args[]) throws IOException{
        N = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while(st.hasMoreTokens()){
            list.add(Integer.parseInt(st.nextToken()));
        }
        if(N==1){
            result = list.get(0);
        }else{

            
            Collections.sort(list);
            asc = new int[N];
            for(int i=0;i<N;i++){
                asc[i]=list.get(i);
            }
            
            Collections.sort(list,Collections.reverseOrder());
            
            desc = new int[N];
            Arrays.fill(desc, 0);
            
            if(N%2==0){
                for(int i=0;i<N;i++){
                    desc[i]=list.get(i);
                }
            }else{
                for(int i=0;i<N;i++){
                    desc[i]=list.get(i);
                }
            }
            
            result = desc[0];
            for(int i=0;i<N/2+1;i++){
                int temp=desc[i+1]-asc[i];
                if(temp>0){
                    result+=temp;
                }
            }
            
        }
        System.out.println(result);
    }
}

실력이 음수가 되는 경우는 모두 0으로 계산하기 때문에, 실력의 최댓값이 나오려면
제일 큰수 - 제일 작은수, 그다음큰수 - 그다음 작은수... 의 반복이 되어야 한다. 그러니까

오름차순으로 정렬한 배열하나,
내림차순으로 정렬한 배열하나 해서
배열의 길이의 반까지 큰수-작은수해서 result에 더해다주면된다.
그리고 N이 1이되는경우에는 실력 그대로를 출력하면 된다.

profile
내가 지금 두려워 하고 있는 일이 바로 내가 지금 해야 할 일이다. 🐥

0개의 댓글