Question
https://school.programmers.co.kr/learn/courses/30/lessons/82612
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
Algorithm
- for문을 사용해 price를 count 만큼 곱하며 더해준다.
- 더한 금액과 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);
}
}
'Coding Test > [프로그래머스] Java' 카테고리의 다른 글
[프로그래머스 / Java] Lv.1 내적 (1) | 2025.07.05 |
---|---|
[프로그래머스 / Java] Lv.1 가운데 글자 가져오기 (0) | 2025.07.02 |
[프로그래머스 / Java] Lv.1 제일 작은 수 제거하기 (1) | 2025.06.28 |
[프로그래머스 / Java] Lv.1 콜라츠 추측 (0) | 2025.06.25 |
[프로그래머스 / Java] Lv.1 나누어 떨어지는 숫자 배열 (0) | 2025.06.22 |