출처: https://bumcrush.tistory.com/182 [맑음때때로 겨울]
반응형
package Programmers;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class 최소직사각형 {
    public static void main(String[] args){
        최소직사각형 T = new 최소직사각형();
        int[][] sizes = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        T.solution(sizes);
    }
    public int solution(int[][] sizes) {
        int answer = 0;
        int maxSize = 0;
        //명함의 크기중 가로세로중 작은것의 크기를 담을 집합
        List<Integer> arrMin = new ArrayList<>();
        for (int[] tempI: sizes) {
            //명함을 돌면서 가로세로중 큰수를 maxSize에 담는다.
            maxSize = Math.max(maxSize, Math.max(tempI[0], tempI[1]));
            //작을수들을 arrMin 배열에 담는다.
            arrMin.add(Math.min(tempI[0], tempI[1]));
        }

        //작은수를 담을 배열을 역정렬해준다.
        arrMin.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        //가장큰 크기와 가로세로중 작은크기를 담은 집합중에서의 가장 큰수를 곱해준다.
        answer = maxSize * arrMin.get(0);
        return answer;
    }
}

1. 풀이

  1.1 ) 가로세로 길이중 가장 큰수와 가로세로중 작은수들의 집합중 가장큰수의 곱을 해주면 답을 찾을수있음

  1.2 ) 명함을 돌면서 가장큰수를 maxSize에 담아준다.

  1.3 ) 명함을 돌면서 가로세로중 작은수를 arrMin 에 담아준다. 

  1.4 ) arrMin 역정렬 내림차순으로 정렬해준다.

  1.5 ) maxSize * arrMin의 0번 인덱스(가장큰수) 를 곱해준다.

 

 

※ 지금보니 arrMin굳이 구할필요없이 변수 선언하나 해서 최대값 바로 구해주는게 더 좋을것같다. 

 

 

2. 리팩토링

package Programmers;

import java.util.ArrayList;
import java.util.List;

public class 최소직사각형 {
    public static void main(String[] args){
        최소직사각형 T = new 최소직사각형();
        int[][] sizes = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        T.solution(sizes);
    }
    public int solution(int[][] sizes) {
        int answer = 0;
        int maxSize = 0;
        int subMax = 0;
        //명함의 크기중 가로세로중 작은것의 크기를 담을 집합
        List<Integer> arrMin = new ArrayList<>();
        for (int[] tempI: sizes) {
            //명함을 돌면서 가로세로중 큰수를 maxSize에 담는다.
            maxSize = Math.max(maxSize, Math.max(tempI[0], tempI[1]));
            subMax = Math.max(subMax, Math.min(tempI[0], tempI[1]));
        }
        answer = maxSize * subMax;
        return answer;
    }
}
반응형

+ Recent posts