๋ฌธ์ œ

์›ํ•˜๋Š” ์ƒํ’ˆ์„ ๊ณจ๋ผ ๊ฐ€๊ฒฉ๊ณผ ๋ฐฐ์†ก๋น„๋ฅผ ์ œ์ถœํ•˜๋ผ

ํ˜„์žฌ ์˜ˆ์‚ฐ์œผ๋กœ ์ตœ๋Œ€ ๋ช‡ ๋ช…์˜ ํ•™์ƒ์—์„œ ์„ ๋ฌผ์„ ์‚ฌ์ค„ ์ˆ˜ ์žˆ๋Š”์ง€

์ƒํ’ˆ ํ•˜๋‚˜๋ฅผ 50% ํ• ์ธํ•ด์„œ ์‚ด ์ˆ˜ ์žˆ๋Š” ์ฟ ํฐ ์žˆ๋‹ค. ๋ฐฐ์†ก๋น„๋Š” ํ• ์ธ์— ํฌํ•จ๋˜์ง€ ์•Š๋Š”๋‹ค.

 

์ž…๋ ฅ์˜ˆ์ œ |

์˜ˆ์‚ฐ 28

์ œ์ถœํ•œ ๊ฐ€๊ฒฉ๊ณผ ๋ฐฐ์†ก๋น„ [6, 6], [2, 2], [4, 3], [4, 5], [10, 3]

์ถœ๋ ฅ์˜ˆ์ œ |

4

 

ํ’€์ด

์ด ๋น„์šฉ์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ์„ ํ•œ๋‹ค.

์ฟ ํฐ์„ ์–ด๋–ค ๊ฐ€๊ฒฉ์— ์ ์šฉ์‹œ์ผœ์•ผํ•˜๋Š”๊ฐ€ -> ๊ธฐ์ค€์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๋‹ค ์ฐพ์•„๋ด์•ผํ•œ๋‹ค. 

 

์ฒซ ๋ฒˆ์งธ ์ƒํ’ˆ์„ ํ• ์ธ๋ฐ›๋Š”๋‹ค ์ƒ๊ฐํ•˜๊ณ , ์ด ๋น„์šฉ์—์„œ ์ œ์™ธํ•˜๊ณ  ๊ณ„์‚ฐ

๋‘ ๋ฒˆ์งธ ์ƒํ’ˆ์„ ํ• ์ธ๋ฐ›๋Š”๋‹ค ์ƒ๊ฐํ•˜๊ณ  ์ด ๋น„์šฉ์—์„œ ์ œ์™ธํ•˜๊ณ  ๊ณ„์‚ฐ

.

.

.

๋‹ค ํ•ด๋ณด๋Š” ๊ฒƒ์ด ์™„์ „ํƒ์ƒ‰

 

a[0]+a[1]  ์ƒํ’ˆ๊ฐ€๊ฒฉ+๋ฐฐ์†ก๋น„

 

์ „์ฒด ๋น„์šฉํ•ด์„œ ์ฒซ ๋ฒˆ์งธ ๊ธˆ์•ก์„ ํ• ์ธํ•ด์„œ ๋บ€๋‹ค. → ์นด์šดํŒ…์€ 1๋ถ€ํ„ฐ ์‹œ์ž‘

 

 

์ฝ”๋“œ

const solution = (budget, product) => {
  let answer = 0;
  let n = product.length;

  product.sort((a, b) => (a[0] + a[1]) - (b[0] + b[1])); // ์ดํ•ฉ ์ˆœ์„œ๋Œ€๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ ๋จผ์ €ํ•ด์ฃผ๊ธฐ

  // for๋ฌธ ๋Œ๋ฉด์„œ ๋ชจ๋“  ์ƒํ’ˆ์ด ํ•œ ๋ฒˆ์”ฉ ํ• ์ธ๋ฐ›๋Š” ๊ฒฝ์šฐ ํ•ด๋ณด๊ธฐ
  for (let i = 0; i < n; i++) {
    // ์ „์ฒด ์˜ˆ์‚ฐ ๊ตฌํ•˜๊ธฐ
    let money = budget - (product[i][0] / 2 + product[i][1]); // ํ• ์ธ๋ฐ›์€ ๊ธˆ์•ก์„ ์ „์ฒด ์˜ˆ์‚ฐ์—์„œ ๋บ€๋‹ค.(์‚ฐ ๊ฒฝ์šฐ๋กœ ๊ณ„์‚ฐ)
    let count = 1; // ์œ„์˜ ๊ณ„์‚ฐ์œผ๋กœ 1๊ฐœ๋Š” ๊ณ„์‚ฐํ–ˆ๋‹ค๋Š” ๊ฐ€์ •์œผ๋กœ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•จ
    for (let j = 0; j < n; j++) {
      // i๋Š” ์ด๋ฏธ ํ• ์ธ๋œ ์ƒํ’ˆ์ด๋ฏ€๋กœ j๊ฐ€ i๋ž‘ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ์•ˆ๋˜๋„๋ก ์ฒ˜๋ฆฌ
      if (j !== i && (product[j][0] + product[j][1]) > money) break; // ์‚ฌ๋ ค๊ณ ํ•˜๋Š” ๊ฒƒ์ด ๋‚จ์€ ์˜ˆ์‚ฐ๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ break;
      if (j !== i && (product[j][0] + product[j][1]) <= money) { // ๋‚จ์€์˜ˆ์‚ฐ๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์•„์•ผํ•œ๋‹ค.
        money -= (product[j][0] + product[j][1]); // ์ „์ฒด์—์„œ ๋น„์šฉ ๋นผ์ฃผ๊ธฐ
        count++; // ์ƒํ’ˆ ๊ฐœ์ˆ˜ ์นด์šดํŒ…
      }
    }
    answer = Math.max(answer, count);
  }
  return answer;
}

const budget = 28;
const product = [[6, 6], [2, 2], [4, 3], [4, 5], [10, 3]];
console.log(solution(budget, product));

์ฃผ์„ ์—†๋Š” ์ „์ฒด์ฝ”๋“œ

const solution = (budget, product) => {
  let answer = 0;
  let n = product.length;

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

  for (let i = 0; i < n; i++) {
    let money = budget - (product[i][0] / 2 + product[i][1]); 
    let count = 1;
    for (let j = 0; j < n; j++) {
      if (j !== i && (product[j][0] + product[j][1]) > money) break;
      if (j !== i && (product[j][0] + product[j][1]) <= money) {
        money -= (product[j][0] + product[j][1]);
        count++;
      }
    }
    answer = Math.max(answer, count);
  }
  return answer;
}

const budget = 28;
const product = [[6, 6], [2, 2], [4, 3], [4, 5], [10, 3]];
console.log(solution(budget, product));

+ Recent posts