문제 링크 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
배열이 주어지고 가장 많은 차익을 낼 수 있을때, 차익을 구하는 문제이다.
근데 단순히 배열에서 가장 큰 수 - 가장 작은 수 로만 따지기에는 오류가 날 수 있다.
주어진 테.케를 보고 일단 가장 작은 수를 기준으로 코드를 짜야한다는 생각까지는 했는데.. 테.케를 통과하기 위해서 구현하는데 조금 생각보다 까다로웠다.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
low = prices[0]
profit = 0
for i in prices:
low = min(low, i)
profit = max(profit, i-low)
return profit
근데 가장 작은 값을 기준.. 으로 한다기보다 맨 처음 배열부터 시작하여 값을 비교하면서 새 값을 업데이트하는 방식으로 구할 수 있다는 것을 깨달았다..
2022.04.17 복습
어쩌다보니 5/19 또 복습,,
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy = prices[0]
profit = 0
for i in range(len(prices)):
buy = min(buy,prices[i])
profit = max(profit,prices[i]-buy)
return profit
그래도 내 힘으로 다시 풀어봄
Runtime: 1293 ms, faster than 54.74% of Python3 online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 25.1 MB, less than 39.15% of Python3 online submissions for Best Time to Buy and Sell Stock.