본문 바로가기
코딩테스트

[파이썬] 부족한 금액 계산하기 - 위클리 챌린지 [CODING TEST #11]

by ALTERww 2022. 7. 21.
320x100

https://school.programmers.co.kr/learn/courses/30/lessons/82612

 

 

어렵지 않음..

 

def solution(price, money, count):
    answer = -1
    total = 0
    for n in range(count):
        new_price = price * (n+1)
        total += new_price
    if total > money :
        answer = total - money
    else :
        answer = 0
    
    return answer

 

max 함수와 산술평균을 이용하여 한줄만에 짤 수도 있다.

1부터 count까지의 합은 count * (count + 1) / 2 로 표현할 수 있다. 풀이에서는 몫을 얻는 //를 썼는데 count가 자연수라서 count 혹은 count + 1는 무조건 짝수이기 때문에 /를 써도 된다.

 

def solution(price, money, count):
    return max(0, price * count * (count + 1) / 2 - money)

댓글