-
๐ ๋ฌธ์
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.์์ 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.์์ 2
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.์กฐ๊ฑด
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
๐ ํ์ด
๐ ์ฒซ ๋ฒ์งธ ์๋ (์๊ฐ์ด๊ณผ)
- profit : i๋ฒ์งธ ๋ ์ ํ์์ ๋ ์ป์ ์ ์๋ ์ต๋ ์์ต
- (i๋ฒ์งธ ๋ ์ ๊ฐ๊ฒฉ) - (0~i-1๋ฒ์งธ ๋ ์ค ๊ฐ๊ฒฉ์ด ๊ฐ์ฅ ๋ฎ์๋ ๋ ์ ๊ฐ๊ฒฉ)์ profit์ ์ ์ฅํ๋ ํด๋น ๊ฐ์ด ์์์ด๋ฉด 0์ ์ ์ฅํฉ๋๋ค.
- price[0:i]๋ก ์ฌ๋ผ์ด์ฑํ๋ ๋ถ๋ถ์์ ์๊ฐ์ด๊ณผ๊ฐ ๋ฌ์ต๋๋ค.
class Solution(object): def maxProfit(self, price): profit = [0] * len(price) for i in range(1, len(price)): profit[i] = max(0, price[i] - min(price[0:i])) return max(profit)
โ ๋ ๋ฒ์งธ ์๋ (์ฑ๊ณต)
- profit : i๋ฒ์งธ ๋ ์ ํ์์ ๋ ์ป์ ์ ์๋ ์ต๋ ์์ต
- minprice[i] : 0~i-1๋ฒ์งธ ๋ ์ค ๊ฐ๊ฒฉ์ด ๊ฐ์ฅ ๋ฎ์๋ ๋ ์ ๊ฐ๊ฒฉ
- ์์ ๋ฐฉ๋ฒ๊ณผ ์์ด๋์ด๋ ๋์ผํ๋ minprice๋ฅผ ์ฌ๋ผ์ด์ฑ์ด ์๋ ์์๋น๊ต๋ก ๋ณ๊ฒฝํ์ต๋๋ค.
class Solution(object): def maxProfit(self, price): if len(price) == 1: return 0 elif len(price) == 2: return max(0, price[1] - price[0]) else: minprice = [0] * len(price) profit = [0] * len(price) minprice[0] = 0 profit[0] = 0 minprice[1] = price[0] profit[1] = max(0, price[1] - minprice[1]) for i in range(2, len(price)): minprice[i] = min(minprice[i-1], price[i-1]) profit[i] = max(0, price[i] - minprice[i]) return max(profit)
๊ทธ์น๋ง ํจ์จ์ ์ด์ง ์์ ๋ค์ ํ๊ณ ์ถ์์ต๋๋ค. ๋ฌธ์ ๋ฅผ ๋ค์ ์ฝ์ด๋ณด๋ค๊ฐ ์ด ๋ฌธ์ ๋ ๊ตณ์ด DP๋ก ํ ํ์๊ฐ ์๋ค๋ ๊ฑธ ์์์ต๋๋ค.
โ ์ธ ๋ฒ์งธ ์๋ (์ฑ๊ณต)
- minprice : 0~i๋ฒ์งธ ๋ ์ค ๊ฐ๊ฒฉ์ด ๊ฐ์ฅ ๋ฎ์ ๋ ์ ๊ฐ๊ฒฉ
- 0 <= prices[i] <= 10^4๋ผ๋ ์กฐ๊ฑด์ด ์ฃผ์ด์ก์ผ๋ฏ๋ก minprice๋ฅผ price์ ์ต๋๊ฐ์ธ 10^4๋ก ์ด๊ธฐํํ๊ณ for๋ฌธ์ ๋๋ฉด์ ์ ๋ฐ์ดํธํด์ค๋๋ค.
class Solution(object): def maxProfit(self, price): minprice = 10000 profit = 0 for i in price: profit = max(profit, i - minprice) if i < minprice: minprice = i return profit
ํธ-์
'๐ป Algorithm > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 1966 ํ๋ฆฐํฐ ํ (Deque) (0) 2022.07.02 [Python] LeetCode 20 Valid Parentheses (Stack) (0) 2022.07.02 [Python] ๋ฐฑ์ค - 2579 ๊ณ๋จ ์ค๋ฅด๊ธฐ (DP) (0) 2021.10.26 [Python] ๋ฐฑ์ค - 1912 ์ฐ์ํฉ (DP) (0) 2021.10.25 [Python] ์ด์ฝํ - ์ ๋ ฌ๋ ๋ฐฐ์ด์์ ํน์ ์์ ๊ฐ์ ๊ตฌํ๊ธฐ (์ด์งํ์) (0) 2021.10.20