Thursday, August 20, 2015

Leetcode 121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Easy problem. Just try to record min price and see if now is the best time to sell.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        max_profit, min_price = 0, float("inf")
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)  
        return max_profit
Run Time: 72 ms

No comments:

Post a Comment