프로그래머스 - 최소 직사각형 문제이다.
왼쪽과 오른쪽 값 중 큰 값을 한쪽에 몰아 넣고, 그중 가장 큰 값을 width
그리고 바꾼 상태에서 sizes[i][1] 중 가장 큰 값을 찾아서 height로 정해주었다.
max()를 통해서 접근하고 싶었지만, 2차원 배열에서 max() 사용에 대한 지식이 없어 하지 못했다.
public int solution(int[][] sizes) {
int tmp =0;
for(int i=0;i<sizes.length;i++){
if(sizes[i][0] < sizes[i][1]){
tmp=sizes[i][1];
sizes[i][1]=sizes[i][0];
sizes[i][0]=tmp;
}
}
int maxLeft = sizes[0][0];
int maxRight =sizes[0][1];
for(int i=0 ; i<sizes.length ; i++){
if(maxLeft <= sizes[i][0])
maxLeft = sizes[i][0];
if(maxRight <= sizes[i][1])
maxRight = sizes[i][1];
}
System.out.print(maxLeft + " " + maxRight);
int answer = maxLeft * maxRight;
return answer;
}
max() 를 사용한 풀이가 궁금해졌다.
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;
}
}
나는 Math.max(card[0], card[1]) 부분에 대해 주목했고, 이와 같은 접근이 가능한 이유는 for문에서 card 라는 변수를 int배열로 주었기 때문에 가능한 것을 알게 되었다.