Coding Test/[프로그래머스] Java

[프로그래머스 / Java] Lv.1 부족한 금액 계산하기

annovation 2025. 7. 1. 09:52

Question

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


Algorithm

  1. for문을 사용해 price를 count 만큼 곱하며 더해준다.
  2. 더한 금액과 money를 비교한다.
    • money가 크다면 0을 return
    • 작다면 (더한값 - money)를 return

❗️처음에 sum을 int로 설정했다가 오류가 났었다.


Code

class Solution {
    public long solution(int price, int money, int count) {

        int sum = 0;
        
        // price를 count 만큼 곱하며 더해준다.
        for(int i = 1; i <= count; i++) {
            sum += price * i;
        }
        
        // 더한 금액과 money를 비교
        // 모자란 금액 계산
        if(sum > money) {
            return sum - money;
        } else {
            return 0;
        }
    }
}

 

💡프로그래머스 다른 사람의 풀이

class Solution {
    public long solution(long price, long money, long count) {
        return Math.max(price * (count * (count + 1) / 2) - money, 0);
    }
}