๊ธฐ๋ก๋ฐฉ

Lv.1 : ๋ถ€์กฑํ•œ ๊ธˆ์•ก ๊ณ„์‚ฐํ•˜๊ธฐ ๋ณธ๋ฌธ

CodingTest/Java

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

Soom_1n 2022. 7. 30. 16:22

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • 1๋ถ€ํ„ฐ count๊นŒ์ง€ ์ฆ๊ฐ€์‹œ์ผœ๊ฐ€๋ฉฐ price๋ฅผ ๊ณฑํ•œ ์ด ํ•ฉ์ด money๋ฅผ ๋„˜๋Š”์ง€ ์•Š๋„˜๋Š”์ง€ ํŒ๋ณ„ํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

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

        for(int i = 1; i <= count; i++)
            answer -= price*i;

        if(answer < 0) return -answer;
        else return 0;
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • answer๋Š” -2,500*1 ๋ถ€ํ„ฐ -2,500*2,500๊นŒ์ง€ ๋”ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ long์œผ๋กœ ์ž๋ฃŒํ˜•์„ ์„ ํƒํ–ˆ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ๊ฐ„๋‹จํžˆ ํ’€์—ˆ๋‹ค.
  • ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ, ๋‚ด ์ฝ”๋“œ์˜ if๋ฌธ๋ณด๋‹ค ์ข‹์•˜๋˜ ๋ฐฉ๋ฒ•์€ ์‚ผํ•ญ์—ฐ์‚ฐ์ž์™€ max์—ฐ์‚ฐ์ž ์‚ฌ์šฉ์ด์—ˆ๋‹ค.
    • ๊ฐ€์šฐ์Šค ๋ฒ•์น™(N*(N+1)*0.5) ์œผ๋กœ ๊น”๋”ํžˆ ํ’€์–ด๋‚ธ ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™๋‹ค.
class Solution {
    public long solution(long price, long money, long count) {
        return Math.max(price * (count * (count + 1) / 2) - money, 0);
    }
}
728x90