ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/

๋ฆฌ์ŠคํŠธ์˜ ๊ฐ’์ด N์ดํ•˜ ์ผ ๊ฒฝ์šฐ์—๋Š”, ํ•ด๋‹นํ•˜๋Š” ์ธ๋ฑ์Šค์˜ ๊ฐ’์„ 1 ์ฆ๊ฐ€์‹œํ‚ค๊ณ  N๋ณด๋‹ค ํฐ ๊ฐ’์ธ ๊ฒฝ์šฐ์—๋Š” ๋ชจ๋“  ์ธ๋ฑ์Šค ๊ฐ’์„ ํ˜„์žฌ ๊ฐ’์˜ max๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.

๋ฌธ์ œ ํ’€์ด

๊ฐ ์ธ๋ฑ์Šค์— ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜๋‹ค๊ฐ€, N๋ณด๋‹ค ํฐ ๊ฐ’์ด ๋ฐœ์ƒํ•œ ๊ฒฝ์šฐ answer = max(answer) * N๋กœ ์ฒ˜๋ฆฌํ•˜์˜€๋”๋‹ˆ ํšจ์œจ์„ฑ์„ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜์˜€๋‹ค.

def solution(N, A):
    answer = [0] * N
    for idx in A:
        print(answer)
        if idx > N:
            answer = [max(answer)] * N
        else:
            answer[idx - 1] += 1

    return answer

์ฝ”๋“œ

def solution(N, A):
    answer = [0] * N
    next_max_cnt = max_cnt = 0

    for idx in A:
        if idx <= N:
            current = answer[idx - 1] = max(answer[idx - 1] + 1, max_cnt + 1)
            next_max_cnt = max(current, next_max_cnt)
        else:
            max_cnt = next_max_cnt

    return [cnt if cnt > max_cnt else max_cnt for cnt in answer]
  • ์œ„์˜ ์ฝ”๋“œ์™€ ๋‹ฌ๋ฆฌ max ๊ฐ’์„ ์ฐพ์œผ๋ฉด ์ฆ‰๊ฐ์ ์œผ๋กœ ๋ฐ˜์˜ํ•˜์ง€ ์•Š๋Š”๋‹ค.
  • ๋ชจ๋“  ๊ณผ์ •์ด ๋๋‚œ ํ›„์— cnt ๊ฐ’๊ณผ max_cnt ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ์ฒ˜๋ฆฌํ•˜๋ฉด ํšจ์œจ์„ฑ์„ ๋†’์ผ ์ˆ˜ ์žˆ๋‹ค.
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€