5_hyun
2022. 8. 21. 15:44
반응형
해결법
모든 경우의 수를 다 구해야 하기 때문에 모든 경우를 다 구한 다음에 비교를 하면 된다. 이때 Set에 넣어서 구하면 된다. Set는 중복된 값을 허용하지 않기 때문에 Set를 활용하면 된다. 그리고 Set를 정렬할 때는 Array.from으로 배열로 바꿔서 하면 된다.
내 코드
<html>
<head>
<meta charset="UTF-8" />
<title>출력결과</title>
</head>
<body>
<script>
function solution(n, k, card) {
let answer;
let ary = new Set();
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
let sum = card[i] + card[j] + card[k];
ary.add(sum);
}
}
}
let a = Array.from(ary);
a.sort((a, b) => b - a);
answer = a[k - 1];
return answer;
}
let arr = [13, 15, 34, 23, 45, 65, 33, 11, 26, 42];
console.log(solution(10, 3, arr));
</script>
</body>
</html>
반응형