가장 큰 수

이세진·2022년 4월 15일
0

코테준비

목록 보기
32/87

생성일: 2022년 1월 24일 오후 5:23

구현 코드

# 가장 큰 수
import sys
sys.stdin = open("input2.txt" ,"rt")
n, m = map(int, input().split())

cnt = 0
res = []
n = list(str(n))
n = list(map(int, n))

while len(n) != 0:
    a = n.pop(0)
    if len(res) == 0:
        res.append(a)
    else:
        while len(res) != 0:
            if res[-1] < a and cnt < m:
                res.pop()
                cnt += 1
            else:
                break
        res.append(a)

if cnt < m:
    for _ in range(m-cnt):
        res.pop()

for x in res:
    print(x, end='')
  • 아이디어
    • 주어진 숫자 리스트에서 앞에서부터 하나씩 빼서 res에 넣는데, res에 들어갈 새로운 숫자가 기존에 res에 들어있던 마지막 숫자보다 크다면 해당 숫자 (res[-1])를 계속 제거하면서 넣는다.

모범 답안

import sys
sys.stdin=open("input.txt", "rt")
num, m=map(int, input().split())
num=list(map(int, str(num)))
stack=[]
for x in num:
    while stack and m>0 and stack[-1]<x:
        stack.pop()
        m-=1
    stack.append(x)
if m!=0:
    stack=stack[:-m]
res=''.join(map(str, stack))
print(res)
  • 내가 구현한 코드와 작동 원리는 같으나 간략화 한 코드이다.
profile
나중은 결코 오지 않는다.

0개의 댓글