본문 바로가기
BEB/algorithm

Toy8 - largestProductOfThree

by ddanss 2022. 11. 4.
728x90
//레퍼런스 코드
//사실 3중포문으로도 쉽게 풀리지만
//시간복잡도를 생각하면 레퍼런스 코드가 정말 잘 짠 코드다.

//오름차순으로 정렬한다음
//맨 마지막 3개랑
//맨뒤에꺼 하나와 맨 처음2개를 곱해서 비교한다
//경우의 수를 따져보았다
//-3 -2 -1 4 5 
//-5 -1 3 6 8
//-4 1 3 5 6
//1 2 3 4 5
//이런걸 다 따져봐도 아래 코드로 해보면 결국 최대값은 출력된다

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]; //맨위 3개
  const candi2 = sorted[len - 1] * sorted[0] * sorted[1]; //맨뒤1개와 맨앞 2개
  return Math.max(candi1, candi2); //위에 두개중 최대값
};
반응형

'BEB > algorithm' 카테고리의 다른 글

11 powerSet  (0) 2022.11.09
toy10 binarySearch  (0) 2022.11.08
백트래킹  (0) 2022.11.03
Toy07 - tree dfs  (0) 2022.11.02
Toy06 - Sudoku  (0) 2022.11.02

댓글