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

Contents

๋ฌธ์ œ

์ƒˆ๋กœ ์ƒ๊ธด ๋†€์ด๊ธฐ๊ตฌ๋Š” ์ธ๊ธฐ๊ฐ€ ๋งค์šฐ ๋งŽ์•„ ์ค„์ด ๋Š์ด์งˆ ์•Š์Šต๋‹ˆ๋‹ค. ์ด ๋†€์ด๊ธฐ๊ตฌ์˜ ์›๋ž˜ ์ด์šฉ๋ฃŒ๋Š” 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๋Š” ์ž์—ฐ์ˆ˜

๋‚˜์˜ ํ’€์ด

Python

def solution(price, money, count):
    required_amount = sum(map(lambda x: x * price, range(1, count + 1)))
    return required_amount - money if required_amount > money else 0

JavaScript

function solution(price, money, count) {
  let requiredAmount = 0;
  for (let i=1; i<count+1; i++) {
    requiredAmount += i * price;
  }
  return Math.abs(Math.min(money - requiredAmount, 0));
}

Go

func Abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func solution(price, money, count int) int {
    requiredAmount := 0
    for i := 1; i < count + 1; i++ {
    	requiredAmount += i * price
    }
    return Abs(min(money - requiredAmount, 0))
}

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

Python

def solution(price, money, count): 
    return abs(min(money - sum([price*i for i in range(1,count+1)]),0))

๊ธˆ์•ก์—์„œ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ธˆ์•ก์„ ๋นผ๊ณ  ์–‘/์Œ์ˆ˜ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜์—ฌ ๋ฆฌํ„ดํ•ด์ฃผ๋Š” ๋ฐฉ๋ฒ•๋ณด๋‹ค ๋‘ ๊ฐ’์˜ ์ฐจ์ด๋ฅผ ๊ตฌํ•˜๊ณ  abs๋กœ ์ ˆ๋Œ€๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ๋˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ๋” ๊น”๋”ํ•ด ๋ณด์ด๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

JavaScript

function solution(price, money, count) {
    const tmp = price * count * (count + 1) / 2 - money;
    return tmp > 0 ? tmp : 0;
}

์ด ๋ถ„์€ ๋“ฑ์ฐจ์ˆ˜์—ด์˜ ํ•ฉ ์„ ์ด์šฉํ•ด์„œ ํ•ด๊ฒฐํ•˜์…จ๋‹ค. ์™€์šฐ!

count * (count + 1) / 2 ๋ถ€๋ถ„์„ ๋ณด๋ฉด n(n+1)/2 ๋“ฑ์ฐจ์ˆ˜์—ด ํ•ฉ ๊ณต์‹์ด ๋ณด์ธ๋‹ค. ์—ฌ๊ธฐ์— price๋ฅผ ๊ณฑํ•ด์„œ ๊ธˆ์•ก์˜ ํ•ฉ์„ ์•„์ฃผ ์‰ฝ๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

References


Written by@ugaemi
Record things I want to remember

๐Ÿฑ GitHub๐Ÿ“š Reading Space