알고리즘 & 자료구조/완전 탐색

[프로그래머스 알고리즘 고득점 Kit][완전탐색][Java] 최소직사각형

수수다 2026. 3. 3. 16:48

https://school.programmers.co.kr/learn/courses/30/lessons/86491

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

 

정답 코드

가장 긴 변을 찾으면 모든 명함의 가로 세로 중 긴 변을 포함할 수 있다.
그러면 명함들의 긴 변들을 가장 긴 변에 맞춰 넣고
나머지 변들 중에 최대가 나머지 사이즈가 될 것이다.

 

 

나는 스왑을 하긴 했지만 다하고 나니 그냥


widthMax = Math.max(widthMax, Math.max(sizes[i][0], sizes[i][1])); 

heightMax = Math.max(heightMax, Math.min(sizes[i][0], sizes[i][1])); 

이렇게 한번의 반복문으로 끝낼 수 있음을 깨달았다.

class Solution {
    public int solution(int[][] sizes) {
        int num = sizes.length;

//주어진 사이즈의 긴 변 중 최대와 
//주어진 사이즈의 짧은 변 중 최대가 모든 명함이 들어가면서 최소가 되는 사이즈.
        for(int i=0; i<num; i++){
            if(sizes[i][0] < sizes[i][1]) {
                int temp = sizes[i][0];
                sizes[i][0] = sizes[i][1];
                sizes[i][1] = temp;
            }
        }
        int widthMax = 0;
        int heightMax = 0;
        for(int i=0; i<num; i++){
            widthMax = Math.max(widthMax, sizes[i][0]);
            heightMax = Math.max(heightMax, sizes[i][1]);
        }
        int answer = widthMax * heightMax;
        return answer;
    }
}