[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ง•๊ฒ€๋‹ค๋ฆฌ ๊ฑด๋„ˆ๊ธฐ / ํŒŒ์ด์ฌ / python / ์ด์ง„ํƒ์ƒ‰
Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ง•๊ฒ€๋‹ค๋ฆฌ ๊ฑด๋„ˆ๊ธฐ / ํŒŒ์ด์ฌ / python / ์ด์ง„ํƒ์ƒ‰

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿ’ก solutions  

๐Ÿ’ฌ ์ˆœ์ฐจํƒ์ƒ‰์œผ๋กœ๋Š” ํšจ์œจ์„ฑ์„ ๋งŒ์กฑํ•˜๊ธฐ ์–ด๋ ต๊ธฐ ๋•Œ๋ฌธ์— ์ด์ง„ํƒ์ƒ‰์œผ๋กœ ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ธ์›์„ ์ฐพ์•„์•ผ ํ•œ๋‹ค.

๐Ÿ’ฌ start๋Š” 1, end๋Š” max(stones) ๋””๋”ค๋Œ์˜ ์ตœ๋Œ“๊ฐ’์œผ๋กœ, mid๋Š” (start+end)//2๋กœ ์„ค์ •

๐Ÿ’ฌ ๋””๋”ค๋Œ์„ ์•ž์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์™€ mid๊ฐ’์„ ๋นผ๊ณ  ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ํ™•์ธ

      -> ๊ฑด๋„ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ cnt += 1 / ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ cnt = 0์œผ๋กœ ์ดˆ๊ธฐํ™”

๐Ÿ’ฌ cnt๊ฐ’์ด k๊ฐœ ์ด์ƒ์ด๋ฉด ๋””๋”ค๋Œ์„ mid๋ช… ๋งŒํผ ๊ฑด๋„ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜๋ณต๋ฌธ break -> end๋ฅผ mid-1 ๋กœ ๊ฐฑ์‹ 

๐Ÿ’ฌ ๋ฐ˜๋ณต๋ฌธ์ด ์˜จ์ „ํžˆ ์ข…๋ฃŒ๋œ ๊ฒฝ์šฐ, ์ฆ‰  mid๋ช…์ด ๋ชจ๋“  ๋””๋”ค๋Œ์„ ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ -> start๋ฅผ mid +1 ๋กœ ๊ฐฑ์‹ 

 

๐Ÿ‘จ‍๐Ÿ’ป code  

def solution(stones, k):
    start = 1
    end = max(stones)
    mid = (start + end) // 2

    while start <= end:
        cnt = 0
        mid = (start + end) // 2
        for stone in stones:
            if (stone - mid) <= 0:
                cnt += 1
                if cnt >= k:
                    end = mid - 1
                    break
            else:
                cnt = 0
        else:
            start = mid + 1
    return start

 

 

๐Ÿ“Œ problem  



๋ฐ˜์‘ํ˜•