๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section04 - 5 - K๋ฒˆ์งธ ํฐ ์ˆ˜

by YWTechIT 2021. 8. 22.
728x90

๐Ÿ“ 33 - K๋ฒˆ์งธ ํฐ ์ˆ˜

100์žฅ์˜ ์นด๋“œ ์ค‘ 3์žฅ์„ ๋ฝ‘๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” 100C3์ด๋ฏ€๋กœ 161,700์ด๋‹ค. ์—ฌ๊ธฐ์„œ 3์žฅ์„ ๋ฝ‘์•„ ๊ฐ ์นด๋“œ์˜ ์ ํžŒ ์ˆ˜๋ฅผ ํ•ฉํ•˜๋ ค๋ฉด 3 ์ค‘๋ฐ˜ ๋ณต๋ฌธ์œผ๋กœ bruteForce๋กœ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋Œ๋ ค๋ณด๋ฉด ๋œ๋‹ค. ์ด ๋ฌธ์ œ์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” ๋‹คํ•ญ ์‹œ๊ฐ„์ธ O(N^3)์ด์ง€๋งŒ N=100์ผ๋•Œ ์ตœ๋Œ€ 1,000,000๋ฒˆ ์ˆ˜ํ–‰ํ•˜๋ฏ€๋กœ ์‹œ๊ฐ„ ์ดˆ๊ณผ์— ๊ฑธ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค. (๋ณดํ†ต ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ ๋•Œ 1์ดˆ๋‹น ์ตœ๋Œ€ 10^8 (์•ฝ 1์–ต๋ฒˆ) ๋Œ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, N=100์ผ๋•Œ๋Š” O(N^4)๊นŒ์ง€๋Š” ์ปค๋ฒ„ ๊ฐ€๋Šฅํ•˜๋‹ค.)

 

๋˜, ๊ฐ•์˜์—์„œ๋Š” 3์ค‘ ๋ฐ˜๋ณต๋ฌธ์˜ i, j, k์˜ ๋ฒ”์œ„๋ฅผ ๋ชจ๋‘ n๊นŒ์ง€๋กœ ์„ค์ •ํ–ˆ๋Š”๋ฐ, ๋งจ ๋งˆ์ง€๋ง‰์—์„œ k๊ฐ€ n์„ ๋ฒ—์–ด๋‚˜๋ฉด ๋ฐ˜๋ณต๋ฌธ์— ๋“ค์ง€ ์•Š๊ณ , ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ j๊ฐ€ n์˜ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋„ ๋ฐ˜๋ณต๋ฌธ์— ๋“ค์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์ž๋™์ ์œผ๋กœ ์ข…๋ฃŒ๋œ๋‹ค๊ณ  ๋ง์”€ํ•˜์…จ๋‹ค. ๋‚˜๋Š” ์กฐ๊ธˆ์ด๋ผ๋„ ๋ถˆ ํ•„์š”ํ•œ ์—ฐ์‚ฐ์„ ์ค„์ด๊ธฐ ์œ„ํ•ด ๋ฐ˜๋ณต๋ฌธ์˜ ๋ฒ”์œ„๋ฅผ n-2, n-1, n๊นŒ์ง€๋กœ ์„ค์ •ํ–ˆ๋‹ค.

 

728x90

 

// ๋‚˜์˜ ์ฝ”๋“œ
let arr = [13, 15, 34, 23, 45, 65, 33, 11, 26, 42];
let target = 3;
let n = 10;

console.log(solution(n, target, arr))

function solution(n, target, arr){
    let answer = [...new Set([])];

    for (let i=0; i<n-2; i++){
        for (let j=i+1; j<n-1; j++){
            for (let k=j+1; k<n; k++){
                answer.push(arr[i] + arr[j] + arr[k]);
            }
        }
    }
    answer = answer.sort((a, b) => b - a);
    return answer[target-1];
}

 

// ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ
let arr = [13, 15, 34, 23, 45, 65, 33, 11, 26, 42];
let target = 3;
let n = 10;

console.log(solution(n, target, arr))

function solution(n, k, arr) {
    let ans = new Set();

    for (let i = 0; i < n - 2; i++) {
      for (let j = i + 1; j < n - 1; j++) {
        for (let k = j + 1; k < n; k++) {
          ans.add(arr[i] + arr[j] + arr[k]);
        }
      }
    }
    ans = Array.from(ans).sort((a, b) => b - a);
    return ans[k - 1];
  }
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€