class Solution {
public long solution(int price, int money, int count) {
long total = (long) price * (count * (count + 1)) / 2;
long answer = total - money;
return answer > 0 ? answer : 0;
}
}
놀이기구를 N 번째 이용한다면 원래 이용료의 N배를 받는다면
일정한 수만큼 커지기 때문에
1
부터 count
까지의 합을 구하는 공식을 사용 (ex. 3+6+9+...
)
1 + 2 + 3 + ... + count = (count / 2) x (2 x 1 + (count - 1) x 1)
= (count / 2) x (2 + count - 1)
= (count / 2) x (count + 1)
= (count x (count + 1)) / 2
23개의 테스트 케이스 중 22개 통과, 1개 실패한 코드
class Solution {
public long solution(int price, int money, int count) {
long answer = 0;
long total = 0;
for(int i=1; i<=count; i++){
total += (long) price*i;
}
answer = total - money;
return answer;
}
}