[프로그래머스] Level1. 최소직사각형

Benjamin·2023년 3월 17일
0

프로그래머스

목록 보기
49/58


처음에 어떻게 풀어야하나 막막했다.

가로와 세로의 최대길이와 각각 인덱스를 저장해둔 후, 원래 케이스와 각각 뒤집었을때에도 서로의 최대를 넘지 않는지, 둘 다 같이 뒤집었을때는 어떨지 이렇게 총 4개의 케이스로나누어서 생각해야하나 코드가 너무 지저분해지는데 고민하다가 이 방법은 아닌것같아 해설을 찾아봤다.

로직

가로와 세로의 틀에 얽매이지 말자!
가로: 두 변중에서 긴 부분
세로: 두 변중에서 작은 부분
이렇게 생각하면 놀랍게도 정말 쉽게 풀리는 문제이다.

그후, 가로와 세로의 길이가 모두 다 들어가게, Max(가로)와 Max(세로)를 설정하면 정말 쉽게풀린다.

내 풀이

class Solution {
    public int solution(int[][] sizes) {
        int widthMax = 0;
        int heightMax = 0;
        for(int i=0; i<sizes.length; i++) {
            int width = Math.max(sizes[i][0], sizes[i][1]);
            int height = Math.min(sizes[i][0], sizes[i][1]);
            sizes[i][0] = width;
            sizes[i][1] = height;
            if(widthMax < sizes[i][0]) widthMax = sizes[i][0];
            if(heightMax < sizes[i][1] ) heightMax = sizes[i][1];
        }
        int answer= widthMax*heightMax;
        return answer;
    }
}

다른 풀이

class Solution {
    public int solution(int[][] sizes) {
        int length = 0, height = 0;
        for (int[] card : sizes) {
            length = Math.max(length, Math.max(card[0], card[1]));
            height = Math.max(height, Math.min(card[0], card[1]));
        }
        int answer = length * height;
        return answer;
    }
}

내가 풀었던 풀이를 향상된 for문과 이차원 배열을 1차원 배열로 받으면 열의 개수만큼 1차원 배열의 크기로 들어가는 것을 이용해 이중 Math.max()를 이용하면 더 간단한 코드가 된다.

0개의 댓글