문제 링크: https://neetcode.io/problems/buy-and-sell-crypto
NeetCode
neetcode.io
투 포인터/슬라이딩 윈도우
[내 풀이]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
for i in range(len(prices)-1):
for j in range(i, len(prices)):
profit = prices[j] - prices[i]
if profit > maxProfit:
maxProfit = profit
return maxProfit
비효율적인 코드.. 그냥 범위가 작아서 쓸수 있는 코드...
[솔루션]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
lowest = prices[0]
for price in prices:
if price < lowest:
lowest = price
res = max(res, price - lowest)
return res
시간 복잡도
n이 prices의 길이일 때,
내 코드: O(n^2)
솔루션: O(n)
'Algorithm > NeetCode' 카테고리의 다른 글
[NeetCode/Python] Meeting Schedule (0) | 2024.10.02 |
---|---|
[NeetCode/Python] Min Cost Climbing Stairs (0) | 2024.09.19 |
[NeetCode/Python] Kth Largest Integer in a Stream (0) | 2024.09.03 |
[NeetCode/Python] Two Integer Sum (0) | 2024.08.31 |
[NeetCode/Python] Plus One (2) | 2024.08.30 |