| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 
| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
| 19 | 20 | 21 | 22 | 23 | 24 | 25 | 
| 26 | 27 | 28 | 29 | 30 | 31 | 
													Tags
													
											
												
												- solidity
- External Call
- DPOS
- 알고리즘
- 백준
- 블록체인 기술
- DEFI
- Crash
- .dsym
- PBFT
- ios
- pow
- view 이동
- viewcontroller
- 블록체인
- 이더리움
- Mining
- 암호화폐
- dsYM
- Report
- POS
- reentrancy
- 비트코인
- 프로그래머스
- Algorithm
- 분산원장
- Xcode
- Blockchain
- 재진입공격
- ethereum
													Archives
													
											
												
												- Today
- Total
개발하기좋은날
largestProductOfThree 본문
반응형
    
    
    
  정수를 요소로 갖는 배열을 입력받아 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 (3) | 2022.05.25 | 
| isSubsetOf (1) | 2022.05.24 | 
			  Comments