Time Complexity: O(N)
Space Complexity: O(N) (Worst -> len(maxlist) = n/2
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
n1, n2 = 0, 1
minlist = []
for i in range(len(prices) - 1):
if prices[i] < prices[n1]:
if prices[n2] - prices[n1] > 0:
minlist.append(prices[n2] - prices[n1])
n1 = i
n2 = i + 1
elif prices[i+1] > prices[n2]:
n2 = i + 1
if prices[n2] - prices[n1] > 0:
minlist.append(prices[n2] - prices[n1])
return max(minlist) if minlist else 0
'CS > 알고리즘' 카테고리의 다른 글
[Leetcode] 1491. Average Salary Excluding the Minimum and Maximum Salary (0) | 2023.05.02 |
---|---|
[Leetcode] 1822. Sign of the Product of an Array (0) | 2023.05.02 |
[Leetcode 334] 334. Increasing Triplet Subsequence (0) | 2023.05.02 |
[Leetcode] 162. Find Peak Element (0) | 2023.05.02 |
[Leetcode] 153. Find Minimum in Rotated Sorted Array (0) | 2023.05.02 |