알고리즘/프로그래머스

[프로그래머스]Lv2. 두 큐 합 같게 만들기(Python)

cha_eyoon 2024. 3. 7. 23:09

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 접근 
  1. 큐를 사용해야 하므로 덱 라이브러리 사용
  2. 원소의 총합이 큰 큐에서 작은 큐로 이동하는 것이 최소 횟수를 보장함을 확인
  3. while 문을 사용해 두 큐의 총합이 같을 때까지 원소가 이동하도록 하고 같거나 같게 만들 수 없는 경우 break

 

코드

 

실패

from collections import deque   # 문제에서 주어진 자료구조 

def solution(queue1, queue2):
    answer = 0
    
    queue1 = deque(queue1)
    queue2 = deque(queue2)
    
    total1 = sum(queue1)
    total2 = sum(queue2)
    
    total = total1 + total2
    limit = len(queue1) * 2
    
    if total % 2 != 0:
        return -1
    
    # 원소의 총합이 큰 큐에서 작은 큐로 이동하는 것이 최소 횟수 보장
    # 하지만 while문 탈출 조건은?
    while True:
        if total1 > total2:
            i = queue1.popleft()
            queue2.append(i)
            total1 -= i
            total2 += i
            answer += 1
        elif total1 < total2:
            i = queue2.popleft()
            queue1.append(i)
            total2 -= i
            total1 += i
            answer += 1
        elif answer == limit:
            answer = -1
            break
        elif total1 == total2:
            break
    
    return answer

 

수정

from collections import deque   # 문제에서 주어진 자료구조 

def solution(queue1, queue2):
    answer = 0
    
    queue1 = deque(queue1)
    queue2 = deque(queue2)
    
    total1 = sum(queue1)
    total2 = sum(queue2)
    
    total = total1 + total2
    limit = len(queue1) * 4
    
    if total % 2 != 0:
        return -1
    
    # 원소의 총합이 큰 큐에서 작은 큐로 이동하는 것이 최소 횟수 보장
    # 하지만 while문 탈출 조건은?
    while True:
        if total1 > total2:
            i = queue1.popleft()
            queue2.append(i)
            total1 -= i
            total2 += i
            answer += 1
        elif total1 < total2:
            i = queue2.popleft()
            queue1.append(i)
            total2 -= i
            total1 += i
            answer += 1
        else:
            break
        
        if answer == limit:
            answer = -1
            break 
    
    return answer