이번에 풀어 본 문제는 프로그래머스의 체육복이라는 문제이다. LV1 문제지만 몇번이나 테스트 케이스를 통과하지 못했던 문제다.
문제의 알고리즘은 그리디(Greedy) 알고리즘이다.
먼저 내가 틀렸던 코드를 살펴보자.
.
.
def solution(n, lost, reserve):
count = 0
cloth = [0]
for i in range(1, n + 1):
cloth.append(1)
for i in reserve:
cloth[i] += 1
for i in lost:
cloth[i] -= 1
# [0, 2,0,2,0,2]
for i in range(1, n + 1):
if cloth[i] == 0:
if cloth[i - 1] > 1:
cloth[i] += 1
cloth[i - 1] -= 1
if i < n and cloth[i + 1] > 1:
cloth[i] += 1
cloth[i + 1] -= 1
for i in cloth:
if i > 0:
count += 1
return count

성공한 코드를 보며 이유를 알아보자
def solution(n, lost, reserve):
count = 0
cloth = [1] * (n + 1)
for i in reserve:
cloth[i] += 1
for i in lost:
cloth[i] -= 1
for i in range(1, n + 1):
if cloth[i] == 0:
if cloth[i - 1] > 1:
cloth[i] += 1
cloth[i - 1] -= 1
elif i < n and cloth[i + 1] > 1:
cloth[i] += 1
cloth[i + 1] -= 1
for i in range(1, n+1):
if cloth[i] > 0:
count += 1
return count
❌ 틀렸던 코드
if cloth[i - 1] > 1:
cloth[i] += 1
cloth[i - 1] -= 1
if i < n and cloth[i + 1] > 1:
cloth[i] += 1
cloth[i + 1] -= 1
✅ 정답 코드
if cloth[i - 1] > 1:
cloth[i] += 1
cloth[i - 1] -= 1
elif i < n and cloth[i + 1] > 1:
cloth[i] += 1
cloth[i + 1] -= 1