알고리즘 공부/위클리 챌린지

프로그래머스 위클리 챌린지 8주차 - java

철매존 2021. 9. 27. 11:00
728x90
반응형

문제 설명

1. 명함의 가로, 세로 크기가 주어진다.

2. 명함을 담을 수 있는 가장 작은 크기의 명함지갑의 크기를 return하면 된다.

3. 명함은 눕혀서 보관할 수도 있고, 세워서 보관할 수도 있다(가로세로 위치 상관x)

풀이 과정

 1. 굉장히 간단한 문제이다.

 2. 명함의 가로, 세로 기준으로 긴 값과 짧은 값들을 저장한다.

 3. 긴 값들의 최대값, 짧은 값들의 최대값을 곱하면 답을 구할 수 있다.

 4. 여기서 구현한 코드는 process별로 나누어서 길게 나왔지만, 실제로는 짧은값 긴값 두개를 만들어서 이를 바로바로 구하면 for문을 한 번만 사용해서도 충분히 구할 수 있을 것이다.

코드

class Solution {
public int solution(int[][] sizes) {
int answer = 0;
int bigMaxLength = 0;
int smallMaxLength = 0;
int sizesLonger[] = new int[sizes.length];
int sizesShorter[] = new int[sizes.length];
for(int i=0; i<sizes.length; i++){
sizesLonger[i] = Math.max(sizes[i][0], sizes[i][1]);
sizesShorter[i] = Math.min(sizes[i][0], sizes[i][1]);
}
for(int i=0; i<sizes.length; i++)
bigMaxLength = Math.max(bigMaxLength, sizesLonger[i]);
for(int i=0; i<sizes.length; i++)
smallMaxLength = Math.max(smallMaxLength, sizesShorter[i]);
answer = bigMaxLength * smallMaxLength;
return answer;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

코드2

class Solution {
public int solution(int[][] sizes) {
int answer = 0;
int bigMaxLength = 0;
int smallMaxLength = 0;
for(int i=0; i<sizes.length; i++){
if(sizes[i][0] > sizes[i][1]){
bigMaxLength = Math.max(bigMaxLength, sizes[i][0]);
smallMaxLength = Math.max(smallMaxLength, sizes[i][1]);
}else{
bigMaxLength = Math.max(bigMaxLength, sizes[i][1]);
smallMaxLength = Math.max(smallMaxLength, sizes[i][0]);
}
}
answer = bigMaxLength * smallMaxLength;
return answer;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
반응형