프로그래머스 - 최소 직사각형[java]

스브코·2021년 11월 12일
0

문제 출처: https://programmers.co.kr/learn/courses/30/lessons/86491

문제 설명

자세한 설명은 출처 참조.

가로 길이와 세로 길이를 교환 하여 최소 크기의 최대 가로 길이 * 최대 세로 길이를 출력하면 된다.

문제 풀이

class Solution {
    public int solution(int[][] sizes) {
        int col = -1;
        int max = -1;
        
        for(int i = 0; i < sizes.length; i++) {
            for(int j = 0; j < sizes[0].length; j++) {
                if (sizes[i][j] > max) {
                    col = j;
                    max = sizes[i][j];
                }
            }
        }
        
        int otherCol = col == 0 ? 1 : 0;
        int otherMax = -1;
        
        for(int i = 0; i < sizes.length; i++) {
            if(sizes[i][col] < sizes[i][otherCol]) {
                int temp = sizes[i][col];
                sizes[i][col] = sizes[i][otherCol];
                sizes[i][otherCol] = temp;
            }
            if(sizes[i][otherCol] > otherMax)
                otherMax = sizes[i][otherCol];
        }
        
        return max * otherMax;
    }
}

가로와 세로 길이 가 swap을 했을때 최대 가로 길이 * 최대 세로 길이의 크기가 줄어 드는걸 찾는게 포인트라 for loop을 두번 돌렸는데, 다른 문제 풀이를 보니 참 쉽게 푸는 방법이 있었다.

다른 풀이

class Solution {
    public int solution(int[][] sizes) {
        int max = 0;
        int min = 0;
        for (int[] size : sizes) {
            int paramMax = Math.max(size[0], size[1]);
            int paramMin = Math.min(size[0], size[1]);

            if (paramMax > max) {
                max = paramMax;
            }

            if (paramMin > min) {
                min = paramMin;
            }
        }
        return max * min;
    }
}

솔직히 이거를 보고 오.. 이렇게 되네 생각은 했지만 문제를 보고 이렇게 될거라고 생각이 나는 들거 같진않다......

profile
익히는 속도가 까먹는 속도를 추월하는 그날까지...

0개의 댓글