Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 15, 2017 21:50
Show Gist options
  • Save cixuuz/aa0f245e12b46d3f06b18f1d32feb0ca to your computer and use it in GitHub Desktop.
Save cixuuz/aa0f245e12b46d3f06b18f1d32feb0ca to your computer and use it in GitHub Desktop.
[121. Best Time to Buy and Sell Stock] #leetcode
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