Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$
  • Runtime 1122ms
  • Beats 36.62%


Solution

from typing import List


class Solution:
    # prices[i] -> i๋ฒˆ์งธ ๋‚ ์˜ ์ฃผ์‹์˜ ๊ฐ€๊ฒฉ
    # ์–ด๋Š ํ•˜๋ฃจ์— ์ฃผ์‹์„ ์‚ด ์ˆ˜ ์žˆ๊ณ , "๊ทธ ํ›„" ๋‹ค๋ฅธ ๋‚ ์— ์ฃผ์‹์„ ํŒ” ์ˆ˜ ์žˆ์Œ.
    # ์‹คํ˜„ ๊ฐ€๋Šฅํ•œ ๊ฐ€์žฅ ํฐ ์ด์ต (return the maximum profit) ๊ตฌํ•˜์ž! -> ์–ด๋–ค ์ด์ต๋„ ์—†์„ ๊ฒฝ์šฐ 0 ๋ฆฌํ„ด

    # O(n)
    # ์ฃผ์‹์ด ๊ฐ€์žฅ ์ €๋ ดํ–ˆ์„ ๋•Œ๋ฅผ ์ƒ๊ฐํ•˜์ž -> ๊ฐ ์‹œ์ ์—์„œ์˜ ์ตœ๋Œ€ ์ด์ต ๊ตฌํ•  ์ˆ˜ ์žˆ์Œ
    def maxProfit(self, prices: List[int]) -> int:
        # ์ตœ๋Œ€ ์ด์ต -> ์–ด๋–ค ์ด์ต์ด ์—†์„ ๊ฒฝ์šฐ 0์„ ๋ฆฌํ„ดํ•˜๋‹ˆ ์ดˆ๊ธฐ๊ฐ’ 0์œผ๋กœ ์„ธํŒ…
        max_profit = 0
        # ๊ณผ๊ฑฐ์˜ "์ตœ์ € ์ฃผ๊ฐ€" -> ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ ์ฒซ๋ฒˆ์งธ ์š”์†Œ ์„ธํŒ…
        min_price = prices[0]

        # prices: i๋ฒˆ์งธ์˜ ์ฃผ์‹์˜ ๊ฐ€๊ฒฉ ๋ฐฐ์—ด -> price: ๊ทธ ์ฃผ์‹์˜ ๊ฐ€๊ฒฉ
        for price in prices:
            # ํ˜„์žฌ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ๊ทธ ์‹œ์ ์—์„œ์˜ ์ตœ๋Œ€ ์ด์ต ๊ณ„์† ๊ฐฑ์‹ 
            # price์—์„œ min_price๋ฅผ ๋นผ์ฃผ๋Š” ์ด์œ ๋Š”
            # ์ตœ๋Œ€ ์ด์ต์€ ํ˜„์žฌ ์ฃผ๊ฐ€์—์„œ ๊ณผ๊ฑฐ์˜ ์ตœ์ € ์ฃผ๊ฐ€๋ฅผ ๊ทธ๋ƒฅ ๋นผ์ฃผ๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ
            # ํ˜„์žฌ ์ฃผ๊ฐ€์—์„œ ๊ณผ๊ฑฐ์˜ ์ตœ์ € ์ฃผ๊ฐ€๋ฅผ ๋นผ์ค€ ๊ฐ’์—์„œ ๋˜ ๊ฐ€์žฅ ํฐ ๊ฐ’์ด ์ตœ๋Œ€ ์ด์ต ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์ด ๋จ
            max_profit = max(price - min_price, max_profit)
            # prices์˜ ์ตœ์†Ÿ๊ฐ’ ๊ณ„์† ๊ฐฑ์‹ 
            min_price = min(price, min_price)

        return max_profit

# O(n^2) -> Time Limit Exceeded๋กœ ์‹คํŒจ
# ๊ฐ€๋Šฅํ•œ ๋ฐฐ์—ด ๋ชจ๋“  ์š”์†Œ์—์„œ ์ฃผ์‹ buy and sell
# def maxProfit(self, prices: List[int]) -> int:
#     # ์–ด๋–ค ์ด์ต์ด ์—†์„ ๊ฒฝ์šฐ 0์„ ๋ฆฌํ„ดํ•˜๋‹ˆ ์ดˆ๊ธฐ๊ฐ’ 0์œผ๋กœ ์„ธํŒ…
#     max_profit = 0
#
#     # len(prices) - 1: ์ฃผ์‹์„ ์‚ฌ๋Š” ๊ฒƒ์€ ๋งˆ์ง€๋ง‰์—์„œ ๋ฐ”๋กœ ์•ž๊นŒ์ง€
#     for buy_stock in range(len(prices) - 1):
#         # ์ฃผ์‹์„ ํŒŒ๋Š” ๊ฒƒ์€ ์‚ฐ ์‹œ์ ์—์„œ ํ•œ์นธ ๋’ค๋ถ€ํ„ฐ ๋งˆ์ง€๋ง‰๊นŒ์ง€
#         for sell_stock in range(buy_stock + 1, len(prices)):
#             # ํ˜„์žฌ ์ด์ต (sell์˜ ์ฃผ์‹ ๊ฐ’ - buy์˜ ์ฃผ์‹ ๊ฐ’)
#             profit = prices[sell_stock] - prices[buy_stock]
#             max_profit = max(profit, max_profit)
#
#     return max_profit

Tags: ,

Categories:

Published:
Updated:

Leave a comment