Created
October 15, 2017 21:50
-
-
Save cixuuz/aa0f245e12b46d3f06b18f1d32feb0ca to your computer and use it in GitHub Desktop.
[121. Best Time to Buy and Sell Stock] #leetcode
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
class Solution(object): | |
def maxProfit(self, prices): | |
""" | |
:type prices: List[int] | |
:rtype: int | |
""" | |
# O(n) O(1) | |
# for each price points, we want to know the lowest price before and | |
# then we can get the max profit | |
# corner case | |
if not prices: | |
return 0 | |
# initial min price and max profit | |
min_price = prices[0] | |
max_profit = 0 | |
# loop price | |
for price in prices: | |
min_price = min(min_price, price) | |
max_profit = max(max_profit, price - min_price) | |
# return | |
return max_profit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment