Publish:

ํƒœ๊ทธ: , , , , ,

์นดํ…Œ๊ณ ๋ฆฌ:

img_3.png

๋ฌธ์ œ

๋ฌธ์ œ ๋งํฌ

img_3.png

img_4.png

์„ค๋ช…

์ค€ํ˜ธ๊ฐ€ ๊ฐ€์ง„ ๋ณ‘์‚ฌ(n) ์™€ โ€˜๋ฌด์ ๊ถŒโ€™ k ๊ฐœ๋ฅผ ์ด์šฉํ•ด ๋ช‡ enemy ๋ฐฐ์—ด์˜ ๋ช‡๋ฒˆ์งธ ์ธ๋ฑ์Šค๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ

ํ’€์ด

  1. ๋ฌด์ ๊ถŒ์€ ์ตœ๋Œ€ํ•œ ์ ๊ตฐ์ด ๋งŽ์€ ๋ผ์šด๋“œ์— ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์œ ๋ฆฌํ•˜๋‹ค. -> PriorityQueue ๋กœ ๋ฌด์ ๊ถŒ์„ ์‚ฌ์šฉ ํ•  ์ ๊ตฐ ์ˆ˜๋ฅผ ๊ฒฐ์ •ํ•˜๊ธฐ ์œ„ํ•ด ์ตœ๋Œ€ ํž™์„ ์‚ฌ์šฉํ•œ๋‹ค.
  2. ๊ฐ ๋ผ์šด๋“œ๋งˆ๋‹ค ์ ์˜ ์ˆ˜๋ฅผ maxHeap ์— ์ €์žฅํ•˜๊ณ , n ์—์„œ ์ ๊ตฐ ์ˆ˜๋ฅผ ์ œ๊ฑฐํ•˜๋ฉด์„œ ์ง„ํ–‰ํ•œ๋‹ค.
  3. ์ค€ํ˜ธ๊ฐ€ ๊ฐ€์ง„ ๋ณ‘์‚ฌ์˜ ์ˆ˜๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋˜๋ฉด, maxHeap ์—์„œ ์ตœ๋Œ€๊ฐ’์„ ๊บผ๋‚ด(maxHeap.poll()) ๋ผ์šด๋“œ๋ฅผ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค.
    • โ€˜๋ฌด์ ๊ถŒโ€™ ์„ ์‚ฌ์šฉํ•œ๋‹ค๋Š” ์˜๋ฏธ : ํž™์—์„œ ๊บผ๋‚ธ ๊ฐ’์„ ๋‹ค์‹œ n ์— ์ถ”๊ฐ€ํ•œ๋‹ค. ์ฆ‰, ์ค€ํ˜ธ์˜ ๋ณ‘์‚ฌ๋ฅผ ๋ณด์ถฉํ•œ๋‹ค.
    • โ€˜๋ฌด์ ๊ถŒโ€™ ์„ ์‚ฌ์šฉํ–ˆ์œผ๋ฏ€๋กœ -1 ํ•˜๊ณ , ๋‹ค์Œ ๋ผ์šด๋“œ๋กœ ๋„˜์–ด๊ฐ”๋‹ค๋Š” ์˜๋ฏธ๋กœ answer ๋ฅผ +1 ํ•ด์ค€๋‹ค.
    • ๋งŒ์•ฝ ์ค€ํ˜ธ์˜ ๋ณ‘์‚ฌ๋„ ์—†๊ณ (n < 0), โ€˜๋ฌด์ ๊ถŒโ€™๋„ ์—†๋‹ค(k < 0)๋Š” ์˜๋ฏธ๋Š” ๋”์ด์ƒ ์ง„ํ–‰์ด ๋ถˆ๊ฐ€๋Šฅ ํ•œ ๊ฒฝ์šฐ์ด๋ฏ€๋กœ break
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int solution(int n, int k, int[] enemy) {
    int answer = 0;
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
    for (int i = 0; i < enemy.length; i++) {
      maxHeap.add(enemy[i]);
      n -= enemy[i];

      if (n < 0) {
        if (k > 0) {
          n += maxHeap.poll();
          k--;
        } else {
          break;
        }
      }
      answer++;
    }
    return answer;
  }
}
๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ