[고득점 kit] 최소직사각형

화낼거양's avatar
Nov 22, 2024
[고득점 kit] 최소직사각형
Contents
문제정답
 
 
 

문제

 
notion image
notion image
 
 
기본적으로 주어진 코드 :
class Solution { public int solution(int[][] sizes) { int answer = 0; return answer; } }
 

정답

 
class Solution { public int solution(int[][] sizes) { int width = 0; int heigth = 0; for (int[] size : sizes) { int a = size[0]; int b = size[1]; if (a < b) { // a와 b를 바꿉니다. int temp = a; a = b; b = temp; } width = Math.max(width, a); heigth = Math.max(heigth, b); } return width * heigth; } }
 
 

배열 순회 및 값 교환

 
for (int[] size : sizes) { int a = size[0]; int b = size[1]; if (a < b) { // a와 b를 바꿉니다. int temp = a; a = b; b = temp; } }
 
  • for (int[] size : sizes): sizes 배열의 각 요소를 순회합니다.
  • int a = size[0]; int b = size[1];: 각 쌍의 첫 번째 값을 a, 두 번째 값을 b로 할당합니다.
  • if (a < b): ab보다 작으면 ab의 값을 교환하여 항상 a가 더 큰 값이 되도록 합니다.
    • int temp = a; a = b; b = temp;: 임시 변수 temp를 사용하여 ab의 값을 교환합니다.
 

최대값 갱신

 
width = Math.max(width, a); heigth = Math.max(heigth, b);
 
  • width = Math.max(width, a); heigth = Math.max(heigth, b);: 현재까지의 최대 너비와 최대 높이 값을 각각 ab를 비교하여 갱신합니다.
 
이후 결과를 반환합니다. (return width * heigth;)
 
Share article

moohyun