Monday, April 14, 2014

Leetcode (Python): Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Solution:


class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        minValue = float("inf")
        maxBenefit = 0
        for price  in prices:
            if minValue > price:
                minValue = price
            if maxBenefit < price - minValue:
                maxBenefit = price - minValue
        return maxBenefit

No comments :

Post a Comment