Codility Lesson6. Sorting - Max Product of Three

세나정·2023년 4월 25일
0
post-thumbnail

Tasks

https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/

내 풀이

// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(A) {
    // Implement your solution here
    A.sort((a,b) => a-b) 
    
    let big = A[A.length-1] * A[A.length-2] * A[A.length-3] 
    let max2 = 0

    if (A[0] < 0 && A[1] < 0 && A[A.length-1] > 0) {
        max2 = A[0] * A[1] * A[A.length-1]

        if (max2 > big) {
            big = max2
        }
    }

    return big
}

곧잘 풀었는데 자꾸 66%에서 머물길래 한참을 생각했는데
결론은 max2 때문이었다.

조건문을 통해 max2의 값을 지정은 해놓지만, 그것이 if가 true일 때만 작동하기에
max2값과 big의 값을 꼭 if문 안에서 해줘야한다!

profile
기록, 꺼내 쓸 수 있는 즐거움

0개의 댓글