프로그래머스/level 1

[프로그래머스][위클리챌린지] 8주차 최소직사각형

binaryJournalist 2021. 9. 30. 18:42
반응형

 

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

 

 

 

** Javascript

 

sort를 이용하여 내림차순으로 바꿔도 되지만 map 자체에서 그냥 비교한 후 바로 배열을 리턴하는 것도 좋다.

 

function solution(sizes) {
    // sizes.map((item) => item.sort((a, b) => b - a));
    sizes = sizes.map(([w, h]) => w < h ? [h, w] : [w, h]);
    let hMax = Math.max.apply(null, sizes.map((item) => item[0]));
    let vMax = Math.max.apply(null, sizes.map((item) => item[1]));
    return hMax * vMax;
}

 

 

** Python

 

def solution(sizes):
    v_max = 0
    h_max = 0
    for v, h in sizes:
        if v < h: v, h = h, v
        if v > v_max: v_max = v
        if h > h_max: h_max = h
    return v_max * h_max

 

 

** Java

 

class Solution {
    public long solution(int[][] sizes) {
        int vMax = 0;
        int hMax = 0;
        for (int[] size : sizes) {
            int temp = 0;
            if (size[1] > size[0]) {
                temp = size[0];
                size[0] = size[1];
                size[1] = temp;
            }
            vMax = size[0] > vMax ? size[0] : vMax;
            hMax = size[1] > hMax ? size[1] : hMax;
        }
        return vMax * hMax;
    }
}

 

반응형