Toy#8 largestProductOfThree

tia·2021년 12월 3일
0

알고리즘

목록 보기
7/9
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)

풀이

1. 도전!

const largestProductOfThree = function (arr) {
  // arr = [2, 1, 3, 7] 
  // 최대값 = [2, 3, 7]

  // arr = [-1, 2, -5, 7]
  // 최대값 = [-5, -1, 7]

  // 발견점
  // 최대값은 arr의 가장 큰 3개의 수를 곱한 값
  
  // 1. 일단 sort
  // 2. 음수인 경우 생각

  const newArr = arr.sort((a, b) => a - b);
  const length = newArr.length - 1;

  const candidate1 = newArr[0] * newArr[1] * newArr[length];
  const candidate2 = newArr[length - 2] * newArr[length - 1] * newArr[length];
  return Math.max(candidate1, candidate2)
};

2. 레퍼런스 코드

const largestProductOfThree = function (arr) {
  const sorted = arr.slice().sort((a, b) => a - b);
  const len = arr.length;
  
  const candi1 = sorted[len - 1] * sorted[len - 2] * sorted[len - 3];
  const candi2 = sorted[len - 1] * sorted[0] * sorted[1];
  return Math.max(candi1, candi2);
};

/*
arr = [-1, 2, -5, 7]

sorted = [-5, -1, 2, 7]
len = 4

candi1 = sorted[3] * sorted[2] * sorted[1] = 7 * 2 * -1 = -14
candi2 = sorted[3] * sorted[0] * sorted[1] = 7 * -5 * -1 = 35

Math.max(candi1, candi2)에 의해서 리턴 값은 35
*/

0개의 댓글

관련 채용 정보