Part3.9_이분탐색(결정알고리즘)&그리디 알고리즘_증가수열 만들기(그리디)

Eugenius1st·2022년 1월 14일
0

Python_algorithm

목록 보기
15/83

증가수열 만들기

내가 생각한 코드

#1. Alt+W+N 입력하고 Alt+W+V :

import sys
from collections import deque # deque import
sys.stdin = open("input.txt", "rt")

n = int(input())
a = list(map(int,input().split()))
a = deque(a)
L = []
max=0

while(a[0] > max or a[-1] > max):
    if a[0] > max and a[-1] > max:
        if a[0] <= a[-1]:
            max = a[0]
            a.popleft()
            L.append("L")
        else:
            max = a[-1]
            a.pop()
            L.append("R")
    else:
        if a[0] > max :
            max = a[0]
            a.popleft()
            L.append("L")
        else:
            max = a[-1]
            a.pop()
            L.append("R")
print(len(L))
for x in L:
    print(x, end="")

선생님 코드

lt 와 rt를 만들어서
a 2 4 5 1 3 중 작은 값을 가져와야 한다.
last 를 0으로 초기화한다.
튜플값으로 (2, L) 같은 느낌으로 저장
(4,L)
(3,R)
...
#정렬한 항에서 첫번째 항을 가져오는 것 !!!
해서 lt 가 rt보다 크거나 lt와 rt 모두 last 보다 클 경우 break 되도록

#1. Alt+W+N 입력하고 Alt+W+V :

import sys
from collections import deque # deque import
sys.stdin = open("input.txt", "rt")

n = int(input())
a = list(map(int,input().split()))
lt = 0
rt = n-1
last =0
res =""
tmp = []

while lt<=rt:
    if a[lt] > last:
        tmp.append((a[lt],'L'))
    if a[rt] > last:
        tmp.append((a[rt],'R'))
    #둘다 받아와서 정렬
    tmp.sort()
    #정렬한 항에서 첫번째 항을 가져오는 것 !!!
    if len(tmp) == 0: # lt와 rt에서 아무것도 가져올 수 없으면 끝냄
        break
    else:
        res= res+tmp[0][1]
        last=tmp[0][0]
        if tmp[0][1] == 'L':
            lt+=1
        else: 
            rt -=1
    tmp.clear()
print(len(res))
print(res)
         
profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글