본문 바로가기
코딩 테스트/알고리즘(Java)

[프로그래머스/Lv.2] 카펫

by KeepCoding 2025. 2. 4.

<문제>

 

<접근 방식>

1) 정사각형 혹은 가로가 긴 직사각형 이기 때문에 두 변의 합은 brwon / 2 + 2 이다.

2) yellow가 1 이상 이기 때문에 가로 및 세로의 길이는 3 이상이여야 한다.

3) 가능한 가로 세로 경우의 수를 구해서 yellow의 격자의 수 와 비교하여 동일하면 return 한다.

 

<코드>

class Solution {
    public int[] solution(int brown, int yellow) {
        int[] answer = new int[2];
        
        int widthAndHeight = brown / 2 + 2;
        
        for(int height = widthAndHeight - 3; height > 0; --height) {
            int yellowSize = (height - 2) * (widthAndHeight - height - 2);
            
            if(yellowSize == yellow) {
                answer[0] = widthAndHeight - height;
                answer[1] = height;
            }
        }
        
        return answer;
    }
}
반응형