Leetcode - Best Time to Buy and Sell Stock 2

Leetcode - Best Time to Buy and Sell Stock 2

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

Daily Leetcode

Hits

๋ฌธ์ œ ๋งํฌ

๋ฌธ์ œ๋Š” ํ•ด์„ํ•˜๋ฉด ์ด๋ ‡๋‹ค. ์ด์ „๊ณผ ๋‹ค๋ฅด๊ฒŒ ๋‹ค์–‘ํ•œ ๋‚ ์งœ์— ์‚ฌ๊ณ ํŒ”๋ ค๊ณ  ํ•œ๋‹ค. ๋‹ค๋งŒ ์ฃผ์‹์€ ํ•œ๋ฒˆ์— ์ตœ๋Œ€ ํ•œ ๊ฐœ๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์•ผ ํ•˜๋ฉฐ ๋™์ผ ๋‚ ์งœ์— ๋งค๋„ ํ›„ ๋งค์ˆ˜๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

์ด๋Ÿฐ ์ƒํ™ฉ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜์ต์„ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.

๐Ÿ“€ Greedy Solution

๋ฌธ์ œ๋ฅผ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๊ณ„์† ์‚ฌ๊ณ ํŒ”๊ณ ๋ฅผ ์ง„ํ–‰ํ•ด์•ผ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ๋‚ด๊ฐ€ ๋‚ด์ผ๋ณด๋‹ค ์‹ธ๊ฒŒ ๋งค์ˆ˜ํ•œ๋‹ค๋ฉด ํ•ญ์ƒ ์ด๋“์ด ์•„๋‹๊นŒ?

์˜ˆ๋ฅผ ๋“ค์–ด [1,2,1,2,8] ๋ฐ์ดํ„ฐ๋ฅผ ๋ณธ๋‹ค๊ณ  ํ•  ๋•Œ ๋‹ต์€ 1์— ๋งค์ˆ˜ 2์— ๋งค๋„ / 1์— ๋งค์ˆ˜ 8์— ๋งค๋„ ๋กœ ์ด 8์˜ ์ˆ˜์ต์„ ์˜ฌ๋ฆด ์ˆ˜ ์žˆ๋‹ค.

ํ•˜์ง€๋งŒ ์œ„ ๋‹ต์€ ๊ฒฐ๊ตญ 1์— ๋งค์ˆ˜ 2์— ๋งค๋„ / 1์— ๋งค์ˆ˜ 2์— ๋งค๋„ / 2์— ๋งค์ˆ˜ 8์— ๋งค๋„ ์™€ ๊ฐ™์œผ๋ฉฐ ํ•ด๋‹น ์ด๋“ ์—ญ์‹œ 8์ด ๋˜๊ฒŒ ๋œ๋‹ค.

์ฆ‰ ์ตœ์ ์˜ ๋งค๋„ ํƒ€์ด๋ฐ์„ ์ฐพ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋‹ค์Œ๋‚ ๋ณด๋‹ค๋งŒ ์‹ธ๋‹ค๋ฉด ๋งค์ˆ˜๋ฅผ ํ•˜๋ฉด ๋˜๋Š” ๊ฒƒ์ด๋‹ค. ์ด๋ฅผ ์•„๋ž˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        days = len(prices)

        profit = 0
        for day in range(days-1):
            if prices[day] < prices[day+1]:
                profit += (prices[day+1] - prices[day])
        return profit
  • TC : O(N)

  • SC : O(1)

๋ฉด์ ‘๊ด€์ด ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋– ์˜ฌ๋ ค๋ณด๋ผ ํ•œ๋‹ค.

๐Ÿชซ Dynamic Programming Solution

์ฃผ์‹ ๋งค๋งค์—๋Š” ๋‘ ๊ฐœ์˜ ์•ก์…˜์„ ์ทจํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ด€๋ง ํ˜น์€ ๋งค์ˆ˜. ๊ทธ๋ ‡๋‹ค๋ฉด ๋‚ด๊ฐ€ ํŠน์ • ๋‚ ์งœ์— ๋งค์ˆ˜ํ–ˆ์„ ๋•Œ, ํ˜น์€ ๋งค์ˆ˜ํ•˜์ง€ ์•Š๊ณ  ๊ด€๋ง๋งŒ ํ•  ๋•Œ๋ฅผ DP๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        days = len(prices)
        STAY, HOLD  = 0, 1

        dp = [[0 for _ in range(days)] for _ in range(2)]
        dp[HOLD][0] = -prices[0]

        for day in range(1, days):
            dp[STAY][day] = max(dp[STAY][day-1], dp[HOLD][day-1]+prices[day])
            dp[HOLD][day] = max(dp[HOLD][day-1], dp[STAY][day-1]-prices[day])

        return dp[STAY][days-1]

STAY๋Š” ๊ด€๋ง์ด๋ฉฐ HOLD๋Š” ์ฃผ์‹์„ ๋ณด์œ ํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ฒซ์งธ๋‚  dp[HOLD]๋Š” ์ฃผ์‹์„ ๋งค์ˆ˜ํ–ˆ๊ธฐ์— ์Œ์ˆ˜๊ฐ’์œผ๋กœ ์ทจํ•ด์ค€๋‹ค.

๊ทธ ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ๋ณธ๊ฒฉ์ ์œผ๋กœ DP๊ฐ€ ์‹œ์ž‘๋œ๋‹ค.

  • ๊ด€๋งํ•˜๋Š” ๊ฒฝ์šฐ : ์ „๋‚ ์— ๊ด€๋งํ–ˆ์„ ๋•Œ ์–ป์€ ์ˆ˜์ต, ๋ณด์œ  ์ค‘์ธ ์ฃผ์‹์„ ๋งค๋„ํ•˜์—ฌ ์ˆ˜์ต์„ ๋‚ด๋Š” ๊ฒฝ์šฐ ์ค‘ ํฐ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
  • ๋งค์ˆ˜ํ•˜๋Š” ๊ฒฝ์šฐ : ์ „๋‚ ์— ๋ณด์œ ํ–‡์„ ๋•Œ ์–ป์€ ์ˆ˜์ต, ์–ด์ œ๊นŒ์ง€ ๊ด€๋งํ•ด์„œ ์–ป์€ ์ˆ˜์ต์—์„œ ์˜ค๋Š˜ ์ฃผ์‹์„ ๋งค์ˆ˜ํ•˜์—ฌ ๋น ์ง„ ๊ฐ’ ์ค‘ ํฐ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.

๋งˆ์ง€๋ง‰์œผ๋กœ ๋ฆฌํ„ดํ•  ๋•Œ๋Š” ๋ฌด์กฐ๊ฑด ๋งค๋„๋ฅผ ํ•ด์•ผ๋˜๊ธฐ์— STAY index๋ฅผ ๋ณด๊ฒŒ ๋œ๋‹ค.

  • TC : O(N)

  • SC : O(N)

์ด๋Ÿฐ ์ƒํ™ฉ์—์„œ๋Š” ํฌ๊ฒŒ DP๊ฐ€ ์™€๋‹ฟ์ง€๋Š” ์•Š๋Š” ๊ฒƒ ๊ฐ™๋‹ค.