Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

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

meeeeejin 2021. 5. 17. 14:52

๋ฌธ์ œ ๋งํฌ: https://programmers.co.kr/learn/courses/30/lessons/64062

 

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

[2, 4, 5, 3, 2, 1, 4, 2, 5, 1] 3 3

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋žŒ์˜ ์ˆ˜๋ฅผ ์ด์ง„ ํƒ์ƒ‰์„ ํ†ตํ•ด ๊ตฌํ•ฉ๋‹ˆ๋‹ค. m๋ช…์˜ ์‚ฌ๋žŒ์— ๋Œ€ํ•ด์„œ ์ƒ๊ฐํ•ด๋ณด๋ฉด, ํ•œ ๋ฒˆ์— ๊ฑด๋„ˆ์•ผ ํ•˜๋Š” ๋””๋”ค๋Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ k๊ฐœ๋ณด๋‹ค ํฌ๋‹ค๋ฉด m๋ช…์˜ ์‚ฌ๋žŒ์€ ๊ฑด๋„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ m๋ณด๋‹ค ์ž‘์€ ๊ฐ’์œผ๋กœ ๋‹ค์Œ ์ด์ง„ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ํ•œ ๋ฒˆ์— ๊ฑด๋„ˆ์•ผ ํ•˜๋Š” ๋””๋”ค๋Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ k๊ฐœ ์ดํ•˜๋ผ๋ฉด m๋ช…์˜ ์‚ฌ๋žŒ์ด ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ m๋ณด๋‹ค ํฐ ๊ฐ’์œผ๋กœ ๋‹ค์Œ ์ด์ง„ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค. 

 

  1. ์ด์ง„ ํƒ์ƒ‰์˜ start, end๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. 
  2. ํ•œ ๋ฒˆ์— ๊ฑด๋„ˆ์•ผ ํ•˜๋Š” ๋””๋”ค๋Œ์˜ ๊ฐœ์ˆ˜ ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. 
    - ๋””๋”ค๋Œ์— ์ ํžŒ ์ˆซ์ž๊ฐ€ ๊ฑด๋„ˆ์•ผ ํ•˜๋Š” ์‚ฌ๋žŒ ์ˆ˜(m) ๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๋งˆ์ง€๋ง‰ ์‚ฌ๋žŒ์€ ํ•ด๋‹น ๋””๋”ค๋Œ์„ ๋ฐŸ์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค. 
  3. m๋ช…์˜ ์‚ฌ๋žŒ์ด ๊ฑด๋„ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ end = m - 1๋กœ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. 
    - ํ•œ ๋ฒˆ์— k๊ฐœ ๋ณด๋‹ค ๋” ๋งŽ์€ ๋””๋”ค๋Œ์„ ๊ฑด๋„ˆ์•ผํ•˜๋Š” ๊ฒฝ์šฐ์ž…๋‹ˆ๋‹ค. 
  4. m๋ช…์˜ ์‚ฌ๋žŒ์ด ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ start = m + 1๋กœ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. 
    - answer = max(answer, m)์„ ํ†ตํ•ด ๊ฐ€๋Šฅํ•œ m๋ช… ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. 
  5. start <= end๋™์•ˆ 2~4๋ฒˆ๋ฅผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค. 

 

 

 

 

์†Œ์Šค์ฝ”๋“œ

def solution(stones, k):
    answer = 0
    start, end = min(stones), max(stones)
    # ์ด์ง„ ํƒ์ƒ‰
    while start <= end:
        m = (start + end) // 2
        # ํ•œ ๋ฒˆ์— ๊ฑด๋„ˆ์•ผ ํ•˜๋Š” ๋””๋”ค๋Œ์˜ ๊ฐœ์ˆ˜ ์ค‘ ์ตœ๋Œ“๊ฐ’
        n, max_jump = 1, 0
        for s in stones:
            if s - m >= 0: 
                max_jump = max(n, max_jump)
                n = 1
            else: # ๋””๋”ค๋Œ์„ ๋ฐŸ์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ
                n += 1
        max_jump = max(n, max_jump)
        
        # m๋ช…์˜ ์‚ฌ๋žŒ์ด ๊ฑด๋„ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ
        if max_jump > k: 
            end = m - 1
        # m๋ช…์˜ ์‚ฌ๋žŒ์ด ๊ฑด๋„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ
        else:
            start = m + 1
            answer = max(answer, m)

    return answer

 

 

 

 

 

728x90