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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section04 - 4 - ์กธ์—…์„ ๋ฌผ

by YWTechIT 2021. 8. 22.
728x90

๐Ÿ“ section04 - 4 - ์กธ์—…์„ ๋ฌผ(bruteForce)

์ƒํ’ˆ์„ ์ตœ๋Œ€ํ•œ ๋งŽ์ด ์‚ฌ์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋Š” ๋น„์šฉ์ด ์ ๊ฒŒ ๋“œ๋Š” ์ƒํ’ˆ๋ถ€ํ„ฐ ํฌํ•จํ•˜๋ฉด ์ตœ๋Œ€ํ•œ ๋งŽ์ด ์‚ด ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์„ ์•Œ๊ณ  ์ด ๋ฌธ์ œ๋ฅผ ํ’€์ž. ๊ทธ๋ฆฌ๊ณ  ์ตœ๋Œ€ ๋ช‡ ๋ช…์˜ ํ•™์ƒ๋“ค์—๊ฒŒ ์‚ฌ์ค„ ์ˆ˜ ์žˆ๋Š”์ง€ ๋ณด๋ ค๋ฉด ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํ•˜๋‚˜์”ฉ ๋”ฐ์ ธ๊ฐ€๋ฉฐ ๊ฒ€์‚ฌ๋ฅผ ๋‹ค ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— bruteForce๋ฅผ ์ด์šฉํ•˜์ž.

 

์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฉด์„œ ๋งจ ์ฒ˜์Œ ์ƒํ’ˆ์€ 50% ํ• ์ธ ์ฟ ํฐ์„ ์‚ฌ์šฉํ•˜๊ณ  ๋‚˜๋จธ์ง€ ์ƒํ’ˆ์„ ๊ตฌ๋งคํ•  ๋•Œ๋Š” ๊ทธ๋ƒฅ ๋”ํ•ด์ฃผ๋ฉด ๋œ๋‹ค. ๋™์ผํ•œ ํ•™์ƒ์ด ์—†์œผ๋ฏ€๋กœ i !== j์ธ ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ๋„ ์žŠ์ง€ ๋ง์ž.

 

// ๋‚˜์˜ ์ฝ”๋“œ
let n = 5;
let m = 28;
let cost = [[6, 6], [2, 2], [4, 3], [4, 5], [10, 3]];

console.log(solution(n, m, cost));

function solution(n, m, cost) {
  let max = Number.MIN_SAFE_INTEGER;

  cost.sort((a, b) => a[0] + a[1] - (b[0] + b[1]));

  for (let i = 0; i < n; i++) {
    let budget = m - (cost[i][0] / 2 + cost[i][1]);
    let cnt = 1;

    for (let j = 0; j < n; j++) {
      if (i === j) continue;
      if (budget - (cost[j][0] + cost[j][1]) >= 0) {
        budget -= cost[j][0] + cost[j][1];
        cnt++;
      } else {
        break;
      }
    }
    max = Math.max(max, cnt);
  }
  return max;
}

 

// ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ
let n = 5;
let budget = 28;

let arr = [[6, 6], [2, 2], [4, 3], [4, 5], [10, 3]];

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

function solution(n, budget, arr){
    let ans = Number.MIN_SAFE_INTEGER;
    arr.sort((a, b) => a[0] + a[1] - (b[0] + b[1]));

    for (let i=0; i<n; i++){
        let cnt = 1;
        let changeBudget = budget - (arr[i][0]/2 + arr[i][1]);
        for (let j=0; j<n; j++){
            if (i === j) continue;

            if (arr[j][0] + arr[j][1] <= changeBudget){
                changeBudget -= arr[j][0] + arr[j][1];
                cnt++
                console.log(arr[j][0] + arr[j][1], changeBudget, cnt)
            }else break;
        }
        ans = Math.max(ans, cnt);
    }
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€