prices
๋ ๋ฐฐ์ด์ด๋ฉฐ, ๊ฐ ์์๋ ๋งค์ผ์ ์ฃผ์ ๊ฐ๊ฒฉ์ด๋ค. ํ ๋ฒ์ฉ๋ง ์ฌ๊ณ ํ ์ ์๋ค๋ฉด,
์ ์ผ ํฐ ์ด์ต์ ์ผ๋ง์ธ์ง ๊ณ์ฐํ๋ ํจ์๋ฅผ ๋ง๋ค์ด๋ผ
input: [7, 1, 5, 3, 6, 4] output: 5
1(2์ผ)์์ ์ฌ์ 6(5์ผ)์ ํ๋ ๊ฒ์ด ๊ฐ์ฅ ํฐ ์์ต
(๋ฏธ๋์ธ 1์์ ์ฌ์, ๊ณผ๊ฑฐ 7์์ ํ๋ ๊ฒ ์๋)
input: [7, 6, 4, 3, 1] output: 0
๋งค์ผ ๊ฐ๊ฒฉ์ด ๋ฎ์์ง๊ธฐ ๋๋ฌธ์ ์์ต์ด ์์
def maxProfit(prices):
#step1
after_price = []
result = set()
#step2
for price in sorted(prices):
if prices.index(price) != len(prices) - 1:
after_price = prices[prices.index(price) + 1:]
else:
after_price = [price]
#step3
profit = max(after_price) - price
if after_price and profit >= 0:
result.add(profit)
return max(result)
๊ฐ๊ฒฉ์ ๋ฎ์ ๊ฐ๊ฒฉ์์ผ๋ก ์ ๋ ฌํ ๋ฆฌ์คํธ๋ฅผ for
๋ฌธ์ผ๋ก ์ํํ๋ฉด์, ๊ฐ๊ฐ์ ๋ํด ๊ฐ์ฅ ํฐ ์์ธ ์ฐจ์ต์ ๊ณ์ฐํ๋ค
์์ธ ์ฐจ์ต์ด 0
์ด์์ด๋ฉด, ๊ทธ ๊ฐ์ result
์ ๋ด๊ณ
๊ฐ์ฅ ํฐ result
๋ฅผ ๋ฐํํ๋ค.
def maxProfit(prices):
#step1
after_price = []
result = set()
ํน์ ๊ฐ๊ฒฉ์ผ ๋, ๊ทธ ๊ฐ๊ฒฉ ์ดํ์ ๊ฐ๊ฒฉ์ ์ ์ฅํ after_price
, ์์ธ ์ฐจ์ต์ ๋ด์ result
๋ฅผ ์์ฑํ๋ค.
def maxProfit(prices):
#... ...#
#step2
for price in sorted(prices):
if prices.index(price) != len(prices) - 1:
after_price = prices[prices.index(price) + 1:]
else:
after_price = [price]
์ ๋ ฌ๋ prices
๋ฅผ ์ํํ๋ฉฐ, price
๋ค์ ๋ฆฌ์คํธ๋ฅผ ์๋ผ after_price
์ ๋ด๋๋ค.
๋ง์ฝ price
๊ฐ prices
๋ฆฌ์คํธ์ ๊ฐ์ฅ ๋ ์์์ด๋ฉด, after_price
๋ฅผ price
๋ง์ ์์๋ก ๊ฐ๋ ๋ฆฌ์คํธ๋ก ์ด๊ธฐํ ํ๋ค.
def maxProfit(prices):
#... ...#
#... ...#
#step3
profit = max(after_price) - price
if after_price and profit >= 0:
result.add(profit)
return max(result)
profit
์ด 0๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๋ค๋ฉด, result
์ ์ถ๊ฐํ๊ณ result
์ max
๊ฐ์ ๋ฐํํ๋ค.