본문 바로가기
Language/Java

[Programmers | Java | 위클리 챌린지] 부족한 금액 계산하기 - Solution with Operator & Math

by ㅇ달빛천사ㅇ 2024. 7. 1.
728x90

KDT 실무형 스프링 백엔드 엔지니어 양성과정 6기  |  Algorithm CODEKATA

💸 부족한 금액 계산하기

 

🏷 관련 주제 : Math Operator 조건문



✔️ Solution with Operator

class Solution {
    public long solution(int price, int money, int count) {
        long answer = 0;
        
        long total = (long) count * (count + 1) / 2 * price;
        
        
        if (total > money) {
            answer = total - money;
        }

        return answer;
    }
}
채점 결과

💥 오늘 만난 문제 & 나의 시도 💦 & 해결 방법 👍

📌 오늘 만난 문제 : 원래 이용료가 price원인 놀이기구의 N번째 이용료는 원래 이용료의 N배입니다.
놀이기구를 count번 타게 되면 현재 자신이 가지고 있는 금액에서 얼마가 모자라는지를 return 하도록 solution 함수를 완성하세요.
단, 금액이 부족하지 않으면 0을 return 하세요.


원래 이용료가 price인 놀이기구의 N번째 이용료N * price
놀이기구를 count번 타게되면 총 이용료는

등차수열의 합 공식에 의해

$\bf{(총 이용료)} = \color{gray}{1 \cdot} \color{navy} {price} \color{gray}{ + 2 \cdot }\color{ navy } {price} \color{gray}{ + 3\cdot }\color{ navy } {price} \color{gray}{ + \cdots + (count - 1) \cdot }\color{ navy } {price} \color{gray}{ + count \cdot }\color{ navy } {price}\\
\qquad\qquad\quad = \color{gray}{ \left\{1 + 2 + 3 + \cdots + (count - 1) + count \right\} \cdot }\color{ navy } {price} \\
\qquad\qquad\quad = \large\bf{\frac{count \cdot (count + 1)}{2} \cdot \color{navy} {price}}$

가지고 있는 금액에서 모자라는 금액을 반환하라고 했으므로
money < (총 이용료) 이면 money - (총 이용료)를 반환
그렇지 않으면 0을 반환

💬 무엇을 새롭게 알았는지

등차수열의 합 공식을 이용해 문제를 풀어보았다.







728x90