๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [2022 KAKAO TECH INTERNSHIP] [Python] Level2_๋‘ ํ ํ•ฉ ๊ฐ™๊ฒŒ ๋งŒ๋“ค๊ธฐ

Dbswnstjd 2022. 12. 16. 05:08

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/118667

 

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

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 2๋‹จ๊ณ„ - ๋‘ ํ ํ•ฉ ๊ฐ™๊ฒŒ ๋งŒ๋“ค๊ธฐ
from collections import deque
def solution(queue1,queue2):
    answer = 0
    queue1 = deque((queue1))
    queue2 = deque((queue2))
    sum_q1 = sum(queue1)
    sum_q2 = sum(queue2)
    limit = len(queue1) * 3
    if (sum_q1 + sum_q2) % 2 != 0:
        return -1
    
    while True:
        if sum_q1 > sum_q2:
            v = queue1.popleft()
            queue2.append(v)
            sum_q1 -= v
            sum_q2 += v
            answer += 1
        elif sum_q1 < sum_q2:
            v = queue2.popleft()
            queue1.append(v)
            sum_q1 += v
            sum_q2 -= v
            answer += 1
        else: 
            break
        if answer == limit:
            answer = -1
            break
        
    return answer

print(solution([1, 2, 1, 2],[1, 10, 1, 2]))

deque๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€์ง€๋งŒ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์™€์„œ limit์ด๋ผ๋Š” ์ œํ•œ์„ ๋‘์—ˆ๋‹ค.