Leetcode :: Arranging Coins

์ˆ‘์ˆ‘ยท2021๋…„ 6์›” 27์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
108/122
post-thumbnail

Problem

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.


Guess

  • ๊ทธ๋ƒฅ ์„ ํ˜• ํƒ์ƒ‰ํ•˜๋ฉด ์‰ฌ์šด ๋ฌธ์ œ์ง€๋งŒ,
  • ์ด๋ถ„ํƒ์ƒ‰์œผ๋กœ๋„ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•ด๋ณด์ธ๋‹ค.
  • ๋“ฑ์ฐจ์ˆ˜์—ด ํ•ฉ๊ณต์‹ k*(k+1)/2 ์œผ๋กœ ์ด๋ถ„ํƒ์ƒ‰์„ ํ†ตํ•ด n์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด k๋ฅผ ์ฐพ์•„๋‚ด๋ฉด ๋œ๋‹ค.

Solution

def arrangeCoins(n):
    left, right = 0, n

    while left <= right:
        mid = (left + right) // 2
        curr = mid*(mid+1) // 2

        if curr == n:
            return mid
        if curr > n:
            right = mid-1
        else:
            left = mid+1
        
    return right
profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€