๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[Algorithm] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.1 : ๋ถ€์กฑํ•œ ๊ธˆ์•ก ๊ณ„์‚ฐํ•˜๊ธฐ

by ์ฝ”๋”ฉ๊ณต์ฑ… 2022. 11. 2.
๋ฐ˜์‘ํ˜•

๋ถ€์กฑํ•œ ๊ธˆ์•ก ๊ณ„์‚ฐํ•˜๊ธฐ

์ƒˆ๋กœ ์ƒ๊ธด ๋†€์ด๊ธฐ๊ตฌ๋Š” ์ธ๊ธฐ๊ฐ€ ๋งค์šฐ ๋งŽ์•„ ์ค„์ด ๋Š์ด์งˆ ์•Š์Šต๋‹ˆ๋‹ค. ์ด ๋†€์ด๊ธฐ๊ตฌ์˜ ์›๋ž˜ ์ด์šฉ๋ฃŒ๋Š” price์› ์ธ๋ฐ, ๋†€์ด๊ธฐ๊ตฌ๋ฅผ N ๋ฒˆ ์งธ ์ด์šฉํ•œ๋‹ค๋ฉด ์›๋ž˜ ์ด์šฉ๋ฃŒ์˜ N๋ฐฐ๋ฅผ ๋ฐ›๊ธฐ๋กœ ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ฆ‰, ์ฒ˜์Œ ์ด์šฉ๋ฃŒ๊ฐ€ 100์ด์—ˆ๋‹ค๋ฉด 2๋ฒˆ์งธ์—๋Š” 200, 3๋ฒˆ์งธ์—๋Š” 300์œผ๋กœ ์š”๊ธˆ์ด ์ธ์ƒ๋ฉ๋‹ˆ๋‹ค. ๋†€์ด๊ธฐ๊ตฌ๋ฅผ count๋ฒˆ ํƒ€๊ฒŒ ๋˜๋ฉด ํ˜„์žฌ ์ž์‹ ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ธˆ์•ก์—์„œ ์–ผ๋งˆ๊ฐ€ ๋ชจ์ž๋ผ๋Š”์ง€๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”. ๋‹จ, ๊ธˆ์•ก์ด ๋ถ€์กฑํ•˜์ง€ ์•Š์œผ๋ฉด 0์„ return ํ•˜์„ธ์š”.


์ œํ•œ ์‚ฌํ•ญ

- ๋†€์ด๊ธฐ๊ตฌ์˜ ์ด์šฉ๋ฃŒ price : 1 โ‰ค price โ‰ค 2,500, price๋Š” ์ž์—ฐ์ˆ˜
- ์ฒ˜์Œ ๊ฐ€์ง€๊ณ  ์žˆ๋˜ ๊ธˆ์•ก money : 1 โ‰ค money โ‰ค 1,000,000,000, money๋Š” ์ž์—ฐ์ˆ˜
- ๋†€์ด๊ธฐ๊ตฌ์˜ ์ด์šฉ ํšŸ์ˆ˜ count : 1 โ‰ค count โ‰ค 2,500, count๋Š” ์ž์—ฐ์ˆ˜

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

price money count result
3 20 4 10

์ž…์ถœ๋ ฅ ์˜ˆ #1
์ด์šฉ๊ธˆ์•ก์ด 3์ธ ๋†€์ด๊ธฐ๊ตฌ๋ฅผ 4๋ฒˆ ํƒ€๊ณ  ์‹ถ์€ ๊ณ ๊ฐ์ด ํ˜„์žฌ ๊ฐ€์ง„ ๊ธˆ์•ก์ด 20์ด๋ผ๋ฉด, ์ด ํ•„์š”ํ•œ ๋†€์ด๊ธฐ๊ตฌ์˜ ์ด์šฉ ๊ธˆ์•ก์€ 30 (= 3+6+9+12) ์ด ๋˜์–ด 10๋งŒํผ ๋ถ€์กฑํ•˜๋ฏ€๋กœ 10์„ return ํ•ฉ๋‹ˆ๋‹ค.


๋ฌธ์ œ ํ’€์ด

sum ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค๊ณ  for๋ฌธ์„ ์ด์šฉํ•˜์—ฌ ๋†€์ด๊ธฐ๊ตฌ ์›๊ฐ€์—์„œ ํšŸ์ˆ˜๋ฅผ ๊ณฑํ•œ ๊ฐ€๊ฒฉ์„ ๊ณ„์†ํ•ด์„œ ์ €์žฅ์‹œํ‚ค๋ฉด sum์—๋Š” 3+6+9+12๋กœ 30์ด ์ €์žฅ๋œ๋‹ค. answer์—๋Š” sum(30)์—์„œ money(20)๋ฅผ ๋บ€ ๊ฐ’ 10์ด ์ €์žฅ๋œ๋‹ค. ์ •๋‹ต์€ 10.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

long long solution(int price, int money, int count) {
    
    long long sum = 0;
    
    for(int i=1; i<count+1; i++){
        sum += price * i;
    }

    long long answer = sum - money;
    
    if (answer <= 0)
        answer = 0;

    return answer;
}

๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ์‹

์ถœ์ฒ˜ : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์Šค์ฟจ

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

long long solution(long price, long money, long count) {
    long long answer = (count + 1) * count / 2 * price; // required
    //long long answer = (5 x 4) รท 2 x 3 == 30

    if (money - answer >= 0)
        return 0;

    return answer - money;
    //30-20 == 10
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€


Reference Book

JavaScript
HTML
CSS
๊ด‘๊ณ  ์ค€๋น„์ค‘์ž…๋‹ˆ๋‹ค.