[프로그래머스] 최소직사각형 86491 (JAVA)

dia·2023년 11월 3일
0

풀이방식

  1. 각 카드의 가로, 세로 길이 중 더 긴 것을 가로로 지정
  2. 가로 중에서 가장 긴 값과 세로 중에서 가장 긴 값을 탐색
  3. 넓이 구하기

구현

첫번째 풀이

public class NUM86491 {
    public static void main(String[] args) {
        int[][] sizes = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        System.out.println(solution(sizes));
    }
    public static int solution(int[][] sizes) {
        int answer = 0;

        int width = 0;
        int height = 0;
        for(int i = 0; i < sizes.length; i++) {
            if(sizes[i][0] < sizes[i][1]) {
                int tmp = sizes[i][0];
                sizes[i][0] = sizes[i][1];
                sizes[i][1] = tmp;
            }
            if(width < sizes[i][0] ) width = sizes[i][0];
            if(height < sizes[i][1] ) height = sizes[i][1];
        }
        answer = width*height;

        return answer;
    }
}

두번째 풀이

public class NUM86491 {
    public static void main(String[] args) {
        int[][] sizes = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        System.out.println(solution(sizes));
    }
    public int solution(int[][] sizes) {
        int answer = 0;

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

첫번째 풀이에서 if문 대신 Math.max, Math.min을 사용해서 간결하게 변경


*다른 분들의 코드를 참고하여 작성했습니다

profile
자기 자신을 위한 CS 메모장 (그림은 지인분이 그려주신 것!)

0개의 댓글