개발하기좋은날

largestProductOfThree 본문

Algorithm

largestProductOfThree

devbi 2022. 6. 2. 14:10
반응형

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

  • 조건
    • 입력의 배열은 음수와 0을 포함하는 정수
    • 입력의 배열 길이는 3이상 
    • 입력의 배열은 중첩되지 않은 1차원 배열  

조합을 이용한 풀이 

const largestProductOfThree = function (arr) {
  
    var com = combination(arr,3)
    com = com.map((v) => {
       return v.reduce((acc, cur) => acc * cur);
    });
    return Math.max.apply(null, com);
};

function combination(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);
  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr.slice(idx + 1);
    const combinationArr = combination(restArr, selectNum - 1);
    const combineFix = combinationArr.map((v) => {
   
        return [fixed, ...v]
    });
    result.push(...combineFix);
  });
  return result;
}


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


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

'Algorithm' 카테고리의 다른 글

BFS를 이용한 primPassword 찾기  (0) 2022.07.05
binarySearch  (0) 2022.06.07
treeDFS  (0) 2022.06.02
Bubble Sort  (0) 2022.05.25
isSubsetOf  (0) 2022.05.24
Comments