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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค • ์ฝ”ํ‹€๋ฆฐ] ๋ถ€์กฑํ•œ ๊ธˆ์•ก ๊ณ„์‚ฐํ•˜๊ธฐ #82612

by ํ‚ค์œค 2023. 11. 6.

#82612

๐ŸŽ„ Question ?

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

//82612

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        var answer: Long = -1
        return answer
    }
}

๐Ÿงฉ Thought Process

  1. use the for loop to find the summation of all the n times of rides.  repeat count times!
    for ๋ฌธ์„ ์ด์šฉํ•ด์„œ ์ด ๊ฐ€๊ฒฉ ์ฐพ๊ธฐ
  2. Then subtract the sum by the money and return that as an answer
    ์ด ํ•ฉ๊ณ„์—์„œ money๋ฅผ ๋นผ์ฃผ๊ณ  ๊ทธ ๊ฐ’์„ answer๋กœ ๋ฆฌํ„ดํ•˜๊ธฐ
  3. Right before returning the answer, check the if the answer is negative using the if clause. If so, return -1.
    answer ๋ฆฌํ„ด ํ•˜๊ธฐ ์ง์ „์— if ๋ฌธ์„ ์ด์šฉํ•˜์—ฌ answer์ด ์Œ์ˆ˜์ธ์ง€ ํ™•์ธํ•˜๊ณ  ์Œ์ˆ˜์ด๋ฉด -1 ๋ฆฌํ„ดํ•˜๊ธฐ
class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        var answer: Long = -1
        var sum: Int = 0
        for (i in 0 until count) {
            sum += price*(i+1)
        }
        if (sum-money >= 0) {
            answer = (sum-money).toLong()
        } else {
            answer = 0
        }
        return answer
    }
}

์ด๋ ‡๊ฒŒ ์ ์—ˆ๋Š”๋ฐ ํ‹€๋ ธ๋‹ค๊ณ  ํ•œ๋‹ค...

์ •ํ™•์„ฑ 82 ํผ์„ผํŠธ.. ์ด๋Ÿด๋•Œ๊ฐ€ ๊ฐ€์žฅ ๋ง‰๋ง‰ํ•˜๋‹ค.. ์–ด์ฉŒ๋ผ๋Š”๊ฑฐ์ง€..:( ๋ชจ๊ฐ€ ๋ฌธ์ œ์ธ๊ฑธ๊นŒ... ์–ด๋–ค ํ…Œ์ŠคํŠธ๋ฅผ ํ–ˆ๋Š”์ง€๋ฅผ ์•Œ๋ฉด ๊ทธ๊ฑธ ๊ณ ์น˜๋ฉด ๋˜๋Š”๋ฐ.. ๊ทธ๊ฒƒ๋„ ์•„๋‹ˆ๋ผ;;

 

ํ˜น์‹œ๋‚˜ ํ•ด์„œ sum์˜ ์ž๋ฃŒํ˜•์„ Long์œผ๋กœ ๋ฐ”๊พธ์–ด์ฃผ์—ˆ๋‹ค. sum์ด ๋ชจ๋“  ๊ฐ’์„ ๋”ํ•œ๊ฑฐ๋‹ˆ๊นŒ ํ›จ ์”ฌ ํฐ ๊ฐ’์„ ๊ฐ€์งˆ๊ฑฐ๋‹ˆ๊นŒ!!

๋๋‹ค!

ํ–‰๋ณต ์งœ๋ฆฟ! ๋ฌด๋ ค 11์  ์งœ๋ฆฌ ๋ฌธ์ œ์˜€๋‹ค :))

๐ŸŽ€ Answer

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        var answer: Long = -1
        var sum: Long = 0
        for (i in 0 until count) {
            sum += price*(i+1)
        }
        if (sum-money >= 0) {
            answer = (sum-money).toLong()
        } else {
            answer = 0
        }
        return answer
    }
}

#2

class Solution {
    fun solution(price: Int, money: Int, count: Int): Long {
        return Math.max(count * (price.toLong() + price * count) / 2L - money, 0)
    }
}
์ถœ์ฒ˜: https://yline.tistory.com/87 [Y_LINE's_Repository:ํ‹ฐ์Šคํ† ๋ฆฌ]

๋‹ค๋ฅธ ํ’€์ด ๋ถ„์„: 2L๋กœ ๋‚˜๋ˆ„์–ด์คŒ์œผ๋กœ์„œ Longํ˜•์„ ์œ ์ง€ํ•ด์ฃผ์—ˆ๋‹ค. maxํ•จ์ˆ˜๋ฅผ ๊ตณ์ด ์‚ฌ์šฉํ–ˆ์–ด์•ผํ•˜๋‚˜ ์‹ถ๊ธด ํ•˜๋‹ค... 

๐ŸŽ Result

๐Ÿ† Comment

Long ์ž๋ฃŒํ˜•์„ ์š”๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋Š” ์ฒ˜์Œ ํ’€์–ด๋ดค๋‹ค. ๋งŽ์ด ๋ฐฐ์›€:)