[Algorithm/Python][SWEA] 1859번 백만 장자 프로젝트

동글이·2022년 11월 6일
0

Algorithm

목록 보기
30/33

[SWEA] 1859. 백만 장자 프로젝트

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&contestProbId=AV5LrsUaDxcDFAXc&categoryId=AV5LrsUaDxcDFAXc&categoryType=CODE&problemTitle=&orderBy=RECOMMEND_COUNT&selectCodeLang=ALL&select-1=2&pageSize=10&pageIndex=1#;return%20false;

- 문제 접근

  • 앞에서부터 접근하는 것이 아닌 뒤에서부터 접근이 핵심!
  • 앞에서부터 접근하면 너무 오래걸려서 런타임 에러가 난다..!
  • 앞으로 출력은 아래와 같이 하는 것이 더 보기 좋을 것 같다.
    print('#{} {}'.format(tc, profit))

- 내 코드

T=int(input())

for t in range(T):
    N=int(input())
    case=list(map(int, input().split()))
    buy=0
    count=0
    profit=0
    now=case[N-1]
    max=0
    for i in range(N-1,0,-1):
        if now>case[i-1]:
            buy+=case[i-1]
            count+=1
            if max<now:
                max=now
        else:
            profit+=(max*count-buy)
            count=0
            buy=0
            now=case[i-1]
    profit += (max * count - buy)
    print("#"+str(t+1)+" "+str(profit))

- 참고할만한 더 멋진 코드

# 테스트 케이스 개수 T 입력
T = int(input())

# T만큼 반복
for tc in range(1, T+1):
    # 자연수 N의 개수 입력
    N = int(input())
    # N 리스트 입력
    N_list = list(map(int, input().split()))

    # N_list의 마지막 값을 최대값으로 설정
    max_value = N_list[-1]
    # 이익 변수 초기화
    profit = 0

    # N-2번째 인덱스부터 0번째 인덱스까지 1씩 감소하면서 반복 순회
    for i in range(N-2, -1, -1):
        # 만약 현재 매매가가 최대값보다 크면 최대값을 변경
        if N_list[i] >= max_value:
            max_value = N_list[i]
        # 현재 매매가가 최대값보다 크지 않으면 차익을 profit 변수에 더해준다
        else:
            profit += max_value - N_list[i]
    
    # 결과 출력
    print('#{} {}'.format(tc, profit))
profile
기죽지 않는 개발자

0개의 댓글