< All posts

2554. Maximum Number of Integers to Choose From a Range I

๋ฌธ์ œ ์„ค๋ช…

์ด ๋ฌธ์ œ๋Š” ๋‘๊ฐœ์˜ ์ •์ˆ˜ n๊ณผ maxSum, ๊ทธ๋ฆฌ๊ณ  banned ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, ๋‹ค์Œ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ตœ๋Œ€์˜ ์ •์ˆ˜ ๋ฐฐ์—ด ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

  • i๋Š” 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ •์ˆ˜์ด๋‹ค.
  • i๋Š” banned ๋ฐฐ์—ด์— ํฌํ•จ๋˜์–ด ์žˆ์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค.
  • i ๊ฐ’๋“ค์„ ์„ ํƒํ•  ๋•Œ ํ•ฉ์ด maxSum์„ ์ดˆ๊ณผํ•˜์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค.
  • i๋Š” ์ค‘๋ณต๋˜์–ด์„œ๋Š” ์•ˆ๋œ๋‹ค.

2554

ํ’€์ด ๋ฐ ํ•ด์„ค

ํ’€์ด

class Solution:
    def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:
        cur_sum = 0
        counter = 0
        i = 1
        
        while 1 <= i <= n:
            if cur_sum + i < maxSum and i not in banned:
                counter += 1
                cur_sum += i
            i += 1
        
        return counter

204/207๊ฐœ ์ผ€์ด์Šค๋ฅผ ๋งž์ท„๋‹ค. ๋ณด๋‹ˆ๊นŒ <= maxSum์„ ํ–ˆ์—ˆ์–ด์•ผ ํ–ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๊ณ ์น˜๋‹ˆ๊นŒ ํ•ด๊ฒฐ๋๋‹ค.

cur_sum = 0
        counter = 0
        banned = set(banned)
        
        for i in range(1, n+1):
            if cur_sum + i <= maxSum and i not in banned:
                counter += 1
                cur_sum += i
            if cur_sum >= maxSum:
                break
        
        return counter

Complexity Analysis

tc

์‹œ๊ฐ„ ๋ณต์žก๋„

  • O(n^2)
    • n๊ฐœ์˜ ์š”์†Œ๋ฅผ ๊ฐ€์ง„ banned ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ, n๊ฐœ์˜ ์š”์†Œ๋ฅผ ๊ฐ€์ง„ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•œ๋‹ค.

๊ณต๊ฐ„ ๋ณต์žก๋„

  • O(n)
    • banned ๋ฐฐ์—ด์„ set์œผ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅํ•œ๋‹ค.

Constraint Analysis

Constraints:
1 <= banned.length <= 10^4
1 <= banned[i], n <= 10^4
1 <= maxSum <= 10^9

References

ยฉ 2025 HyunJoon Sung. All Rights Reserved.

GitHub