Last active
October 31, 2021 22:46
-
-
Save ttungl/65ae9cc4d69b39973ba150071960d23c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def maxProfit(self, prices: List[int]) -> int: | |
| # buy and then sell. | |
| # sol 1: | |
| # time O(n) space O(1) | |
| if not prices: | |
| return 0 | |
| buy_price = float('inf') | |
| max_profit = 0 | |
| for p in prices: # O(n) | |
| if buy_price < p: | |
| max_profit = max(max_profit, p - buy_price) # O(1) | |
| else: | |
| buy_price = min(p, buy_price) | |
| return max_profit | |
| # sol 2: | |
| # time O(n * log n) space O(n) | |
| import heapq | |
| if not prices: | |
| return 0 | |
| buy_price = float('inf') | |
| max_profit = 0 | |
| heap = [] | |
| for p in prices: | |
| if p > buy_price: | |
| heapq.heappush(heap, -(p - buy_price)) | |
| else: | |
| buy_price = p | |
| return -heap[0] if heap else 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment