프로그래머스 탐욕법 문제 풀기
체육복
방법 1 - O(n)
def solution(n, lost, reserve):
students = [1] + [1 for _ in range(n)] + [1]
for i in reserve:
students[i] = 2
for i in lost:
students[i] -= 1
for i in range(len(students)):
if students[i] == 0:
if students[i+1] == 2:
students[i+1] = 1
students[i] = 1
elif students[i-1] == 2:
students[i-1] = 1
students[i] = 1
return students.count(1) + students.count(2) -2
def solution(n, lost, reserve):
u = [1]*(n+2)
for i in reserve:
u[i] += 1
for i in lost:
u[i] -= 1
for i in range(1,n+1):
if u[i-1] == 0 and u[i] == 2:
u[i-1:i+1] = [1,1]
elif u[i] == 2 and u[i+1] == 0:
u[i:i+2] = [1,1]
return len([x for x in u[1:-1] if x > 0])
방법 2 - O(klogk)
def solution(n,lost,reserve):
s = set(lost) & set(reserve)
l = set(lost) - s
r = set(reserve) - s
for x in sorted(r):
if x -1 in l:
l.remove(x - 1)
elif x + 1 in l:
l.remove(x + 1)
return n - len(l)
def solution(n, lost, reserve):
answer = n - len(lost)
tmp = list(set(lost) & set(reserve))
for i in tmp:
lost.remove(i)
reserve.remove(i)
answer = answer + len(tmp)
for i in lost:
for j in reserve:
if j in [i-1,i,i+1]:
reserve.remove(j)
answer = answer + 1
break
return answer
d[i]를 0이 아닌 1로 두는 이유는 0이면 if절에서 False로 인식하기 때문
def solution(n, lost, reserve):
lost_set = set(lost)
reserve_set = set(reserve)
intersection = lost_set & reserve_set
reserve_set -= intersection
lost_set -= intersection
reserve = sorted(list(reserve_set))
d = {}
for i in lost_set:
d[i] = 1
for i in reserve:
if d.get(i-1,False):
del d[i-1]
elif d.get(i+1,False):
del d[i+1]
return n - len(d)
큰 수 만들기
def solution(number, k):
stack = [number[0]]
for num in number[1:]:
while k > 0 and stack and stack[-1] < num:
k -= 1
stack.pop()
stack.append(num)
if k > 0:
stack = stack[:-k]
return ''.join(stack)
조이스틱
def solution(name):
answer = 0
items = [(i,min(ord(t) - ord("A"),ord("Z") - ord(t) + 1)) for i,t in enumerate(name) if t != 'A']
cur = 0
while items:
tmp = get_min_move(items,cur,len(name))
answer += tmp[0]
cur = tmp[1]
return answer
def get_min_move(items,cur,length):
tmps = []
for i,item in enumerate(items):
tmps.append((abs(item[0]-cur),i,item[1],item[0]))
tmps.append((cur+length-item[0],i,item[1],item[0]))
min_item = min(tmps)
items.pop(min_item[1])
return (min_item[0]+min_item[2],min_item[3])