문제 출처: https://programmers.co.kr/learn/courses/30/lessons/86491
문제 설명
가로와 세로의 길이가 들어 있는 array Set이 파라미터로 들어오는데, 모든 set마다의 넓이를 포함 가능한 최소 넓이를 리턴하면된다.
sizes
[[60, 50], [30, 70], [60, 30], [80, 40]]
result
4000
위 입력값을 살펴보면, 가로(column[0]) 의 최대값 80 과 세로(column[1])의 최대값 70을 곱하면 5600이 나오지만, 30과 70을 swap 하여 세로의 최대값을 50으로 낮출 수 있다.
그러므로 80 * 50 = 4000이 리턴된다.
class Solution {
public int solution(int[][] sizes) {
int col = -1;
int max = -1;
for(int i = 0; i < sizes.length; i++) {
for(int j = 0; j < sizes[0].length; j++) {
if (sizes[i][j] > max) {
col = j;
max = sizes[i][j];
}
}
}
int otherCol = col == 0 ? 1 : 0;
int otherMax = -1;
for(int i = 0; i < sizes.length; i++) {
if(sizes[i][col] < sizes[i][otherCol]) {
int temp = sizes[i][col];
sizes[i][col] = sizes[i][otherCol];
sizes[i][otherCol] = temp;
}
if(sizes[i][otherCol] > otherMax)
otherMax = sizes[i][otherCol];
}
return max * otherMax;
}
}
첫번째 nested loop에서 모든 가로, 세로 값들 중의 최대값을 찾고 그게 가로인지 세로인지까지 확인하여 변수로 담아둔다.
최대값이 가로에 포함되어있다면 세로를, 세로에 포함되어 있다면 가로를 스캔하여 최소 넓이를 구하기위해 가로, 세로의 값이 swap이 가능 한지 확인하고 최대값을 구한 후 첫번째 nested loop에서 구한 최대값과 곱하여 return 한다.