Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด๋ถ„ํƒ์ƒ‰ - ์ง•๊ฒ€๋‹ค๋ฆฌ (ํŒŒ์ด์ฌ)

๊ฐ์ž ๐Ÿฅ” 2021. 10. 14. 12:05
๋ฐ˜์‘ํ˜•

 

๋ฌธ์ œ ๋งํฌ

https://programmers.co.kr/learn/courses/30/lessons/43236

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ง•๊ฒ€๋‹ค๋ฆฌ

์ถœ๋ฐœ์ง€์ ๋ถ€ํ„ฐ distance๋งŒํผ ๋–จ์–ด์ง„ ๊ณณ์— ๋„์ฐฉ์ง€์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ์‚ฌ์ด์—๋Š” ๋ฐ”์œ„๋“ค์ด ๋†“์—ฌ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฐ”์œ„ ์ค‘ ๋ช‡ ๊ฐœ๋ฅผ ์ œ๊ฑฐํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋„์ฐฉ์ง€์ ์ด 25๋งŒํผ ๋–จ์–ด์ ธ ์žˆ๊ณ , ๋ฐ”์œ„๊ฐ€

programmers.co.kr

 

๋‚˜์˜ ํ’€์ด

์ด์ „์— ํ’€์—ˆ๋˜ ์ž…๊ตญ์‹ฌ์‚ฌ ์™€ ๋น„์Šทํ•œ ๋ฌธ์ œ๋‹ค. ์ด๋ถ„ํƒ์ƒ‰์˜ ๊ฐœ๋…์„ ํ™•์‹คํžˆํ•˜๊ณ , ์ด ๋ฌธ์ œ์˜ ์œ ํ˜•์€ ํ™•์‹คํ•˜๊ฒŒ ํ’€๊ณ  ๋„˜์–ด๊ฐˆ ์ˆ˜ ์žˆ๋„๋ก ํ•ด์•ผ๊ฒ ๋‹ค ใ… ใ…  

def solution(distance, rocks, n):
    answer = 0
    left = 0
    right = distance
    rocks.sort()

    # left, right, mid๋Š” ๊ฑฐ๋ฆฌ
    while left <= right:
        mid = (left + right) // 2
        remove_rock = 0
        prev_rock = 0
        min_a = 1000000001

        for rock in rocks:
            # ๋งŒ์•ฝ ํ˜„์žฌ ๋Œ๊ณผ, prev๋Œ์˜ ๊ฑฐ๋ฆฌ๊ฐ€ mid๋ณด๋‹ค ์ž‘์œผ๋ฉด, ์‹œ์ž‘์ ์„ mid๋กœ ์˜ฎ๊ฒจ์ค˜์•ผํ•˜๋‹ˆ๊นŒ ์‚ญ์ œํ•˜๊ฒŒ๋˜๊ฒŸ์ง€? 
            if rock - prev_rock < mid:
                remove_rock += 1
            # ๊ทธ๊ฒŒ ์•„๋‹ˆ๋ผ๋ฉด, rock-prev_rock ๊ฐ’์ด min์ด ๋˜๋Š” ๊ฐ’์„ answer์— ์ €์žฅํ•˜๊ณ  prev๋ฅผ rock์œ„์น˜๋กœ ์˜ฎ๊น€ (๋‹ค์Œ rock ๊ฒ€ํ† )
            else:
                min_a = min(min_a, rock-prev_rock)
                prev_rock = rock

        # ์‚ญ์ œํ•œ๋Œ์ด n๋ณด๋‹ค ๋งŽ์œผ๋ฉด ๊ฑฐ๋ฆฌ๋ฅผ ์ค„์—ฌ์ค˜์•ผํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ right๋ฅผ mid-11 ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ๋‹ค์‹œ ใ„ฑ
        if remove_rock > n:
            right = mid-1
        else:
            answer = min_a
            left = mid+1
    return answer
๋ฐ˜์‘ํ˜•