[알고리즘] 3개의 요소를 곱해 나올 수 있는 최대값

Tai Song·2022년 7월 7일
0

알고리즘

목록 보기
1/8
post-thumbnail

정수를 요소로 갖는 배열을 입력받아 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) {
  const sorted = arr.slice().sort((a, b) => a - b); 
  // 배열을 오름차순으로 정렬해 새로운 변수에 담아준다
  const len = arr.length;
  // 배열의 길이를 len 변수에 담아준다
  const candi1 = sorted[len - 1] * sorted[len - 2] * sorted[len - 3];
  // 배열의 길이는 최소 3개 이상이므로, 뒤에서부터 3개의 요소를 먼저 곱해준다 (가장 큰 세 개의 숫자를 곱함)
  const candi2 = sorted[len - 1] * sorted[0] * sorted[1];
  // 앞에서부터 2개와 마지막 요소를 곱해준다 (음수이면 두 개를 곱해서 양수로 만들어주려고)
  return Math.max(candi1, candi2);
  // 두 가지 후보 중 큰 쪽을 리턴한다.
};
profile
Read The Fucking MDN

0개의 댓글