https://school.programmers.co.kr/learn/courses/30/lessons/118667
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 접근
- 큐를 사용해야 하므로 덱 라이브러리 사용
- 원소의 총합이 큰 큐에서 작은 큐로 이동하는 것이 최소 횟수를 보장함을 확인
- 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
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스]Lv2. 광물 캐기(Python) (0) | 2024.03.14 |
---|---|
[프로그래머스]Lv1. 개인정보 수집 유효기간(Python) (2) | 2024.03.14 |
[프로그래머스]Lv3. 파괴되지 않은 건물(Python) (4) | 2024.03.07 |
[프로그래머스]Lv2. 조건에 부합하는 중고거래 상태 조회하기(SQL) (0) | 2024.03.07 |
[프로그래머스]Lv2. 주차 요금 계산(Python) (1) | 2024.03.07 |