https://school.programmers.co.kr/learn/courses/30/lessons/42583
[프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr](https://school.programmers.co.kr/learn/courses/30/lessons/42583)
Approach:
- Pop the first element of
truck_weights
ascurr_truck
- Check the weight of current bridge.
2-1. If current weight +curr_truck
is less than or equal to the weight limitweight
, append to the right of dequebridge
, which keep track of the trucks currently on the bridge.
2-2. If greater thanweight
, pop the first element ofbridge
and addweight - len(bridge)
to the answer. Putcurr_truck
back totruck_weights
. - Repeat until
truck_weights
is empty. The number of leftover trucks onbridge
are added toanswer
. - Return
answer
중간에 아이디어 수정하면서 코드 완성!
from collections import deque
def solution(bridge_length, weight, truck_weights):
answer = 0
truck_weights = deque(truck_weights)
bridge = deque([0 for _ in range(bridge_length)])
sum_bridge = 0
while True:
if len(truck_weights) == 0:
answer += bridge_length
break
curr_truck = truck_weights.popleft()
if sum_bridge - bridge[0] + curr_truck <= weight:
bridge.append(curr_truck)
sum_bridge += curr_truck
off_bridge_truck = bridge.popleft()
sum_bridge -= off_bridge_truck
answer += 1
else:
truck_weights.appendleft(curr_truck)
off_bridge_truck = bridge.popleft()
sum_bridge -= off_bridge_truck
bridge.append(0)
answer += 1
return answer
'알고리즘 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Python/완벽탐색] Level 1 86491 - 최소직사각형 (0) | 2023.08.18 |
---|---|
[프로그래머스/Python/Sort] Level 2 42746 - 가장 큰 수 (0) | 2023.07.17 |
[프로그래머스/Python/Heap] Level 3 42627 - 디스크 컨트롤러 (0) | 2023.07.15 |