Immersive Toy Problem 08

워뇽쿤·2022년 9월 19일
post-thumbnail

문제 : largestProductOfThree

정수를 요소로 갖는 배열을 입력받아 3개의 요소를 곱해 나올 수 있는 최대값을 리턴해야 합니다.

입력

인자 1 : arr

  • number 타입을 요소로 갖는 임의의 배열

출력

  • number 타입을 리턴해야 합니다.

주의사항

  • 입력으로 주어진 배열은 중첩되지 않은 1차원 배열입니다.
  • 배열의 요소는 음수와 0을 포함하는 정수입니다.
  • 배열의 길이는 3 이상입니다.

입출력 예시

let output = largestProductOfThree([2, 1, 3, 7]);
console.log(output); // --> 42 (= 2 * 3 * 7)

output = largestProductOfThree([-1, 2, -5, 7]);
console.log(output); // --> 35 (= -1 * -5 * 7)

풀이

const largestProductOfThree = function (arr) {
    // TODO: 여기에 코드를 작성합니다.
    // 내림차순으로 정렬 후
    // 정렬된 배열의 큰수 3개를 곱한값을 구함 (오른쪽 3개)
    // 정렬된 배열의 큰수 1개와 음수 2개가 있다는 가정하에 곱함 (음수가 -8 이런식이면 - 두개일때 더 큰값이 나올 수 있기 때문)
    // 구해진 두개의 값을 비교해서 더 큰값을 출력하면 됨

    const sorted = arr.slice().sort((a, b) => a - b);   
    //console.log(`1번 : ${sorted}`)
    const len = arr.length;
    //console.log(`2번 : ${len}`)

    const candi1 = sorted[len - 1] * sorted[len - 2] * sorted[len - 3];
    //console.log(`3번 : ${candi1}`)
    //console.log(`3번 : ${sorted[len - 1]} * ${sorted[len - 2]} * ${sorted[len - 3]}`)

    const candi2 = sorted[len - 1] * sorted[0] * sorted[1];
    //console.log(`4번 : ${candi2}`)
    //console.log(`4번 : ${sorted[len - 1]} * ${sorted[0]} * ${sorted[1]}`)

    return Math.max(candi1, candi2);
};
profile
QA 성장기

0개의 댓글