프로그래머스 - 카펫 (Level 2)

2024. 1. 11. 21:17코딩테스트 정리(자바)

728x90

구현은 쉽지만 아이디어 떠올리기가 쉽지 않았던 문제

public class 카펫 {
    public int[] solution(int brown, int yellow) {
        int total = brown + yellow; //타일의 총 합
        int width, height;

        for (height = 3; height <= total / height; height++) {
            //가로의 길이가 세로의 길이보다 크거나 같아야 하므로
            //height는 최소인 3부터 시작
            width = total / height;
            if ((height-2) * (width-2) == yellow) {
                //yellow는 brown에 둘러싸여 있으므로
                //yellow의 개수는 가로,세로 길이에서 각각 2씩 뺀 값을 곱하면 나온다.
                return new int[]{width, height};
            }
        }
		return null; //답을 못찾으면 null 반환
    }
}
728x90