Leetcode - Best Time to Buy and Sell Stock

Leetcode - Best Time to Buy and Sell Stock

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

Daily Leetcode

Hits

๋ฌธ์ œ ๋งํฌ

๋ฌธ์ œ๋Š” ํ•ด์„ํ•˜๋ฉด ๊ฐ€์žฅ ์ˆ˜์ต์„ ๋งŽ์ด ๋‚ผ ์ˆ˜ ์žˆ๋„๋ก ์ €์ ์— ๋งค์ˆ˜, ๊ณ ์ ์— ๋งค๋„ ํ›„ ์–ป๋Š” ์ˆ˜์ต์„ ๋ฆฌํ„ดํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

๐Ÿ”จ Naive Solution

๋”ฑ ๋– ์˜ค๋ฅด๋Š” ์•„์ด๋””์–ด๋Š” ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด ๋ชจ๋“  ๋‚ ์˜ ๊ฐ€๊ฒฉ์„ ์กฐํšŒํ•˜๋ฉด์„œ ๊ฐ€์žฅ ์ €์ ์ด์—ˆ๋˜ ๋‚ ์„ ๋นผ ๋‚˜๊ฐ€๋Š” ๊ฒƒ์ด๋‹ค. ์ฝ”๋“œ๋กœ ๋ณด์ž

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
    """
    ๊ฐ€์žฅ ์ˆ˜์ต์„ ๋งŽ์ด ์–ป์„ ์ˆ˜ ์žˆ๋„๋ก ์ €์ ์— ๋งค์ˆ˜, ๊ณ ์ ์— ๋งค๋„

    ๋งค์ˆ˜์™€ ๋งค๋„๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋‚ 
 
    """

    min_price = max(prices)
    days = len(prices)
    dp = [min_price for _ in range(days)]

    for day in range(days):
        if prices[day] < min_price:
            min_price = prices[day]
        dp[day] = prices[day] - min_price

    return max(dp)
  • TC : O(N)

  • SC : O(N)

dp ๋ฆฌ์ŠคํŠธ๋ฅผ ์“ฐ๋ฉด์„œ ๊ฐ€์žฅ ์ˆ˜์ต์„ ๋งŽ์ด ๋‚ผ ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ•˜๊ณ  ์žˆ๋‹ค. ์ด๋•Œ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์„๊นŒ?

๐Ÿ”ฎ Best Solution

์œ„ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ค๋ณด๋ฉด ๊ตณ์ด dp ๋ฆฌ์ŠคํŠธ๊ฐ€ ํ•„์š”์—†์–ด ๋ณด์ธ๋‹ค. ๊ทธ ์ด์œ ๋Š” ํ•œ ๋ฒˆ ๋ณธ prices๋Š” ๋” ์ด์ƒ ์“ฐ์ด์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

์ฝ”๋“œ๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ์งœ๋ณด์ž.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        """
        ๊ฐ€์žฅ ์ˆ˜์ต์„ ๋งŽ์ด ์–ป์„ ์ˆ˜ ์žˆ๋„๋ก ์ €์ ์— ๋งค์ˆ˜, ๊ณ ์ ์— ๋งค๋„
    
        ๋งค์ˆ˜์™€ ๋งค๋„๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋‚ 
    
        """

        min_price = max(prices)
        days = len(prices)
    
        for day in range(days):
            if prices[day] < min_price:
                min_price = prices[day]
            prices[day] -= min_price
    
        return max(prices)
  • TC : O(N)

  • SC : O(1)

Easy ๋‚œ์ด๋„์˜€์œผ๋ฉฐ ๊ต‰์žฅํžˆ ๋นจ๋ฆฌ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค. ์•„๋ž˜๋Š” ๊ทธ ๊ฒฐ๊ณผ์ด๋‹ค.

image