简体   繁体   中英

Using Python to update min and max values while iterating over a list

I'm working on this problem. My code is below.

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """

        min_stock = 1000000
        max_profit = 0

        for i in range(len(prices)):
            if prices[i] < min_stock:
                min_stock = prices[i]

            if prices[i] - min_stock > max_profit:
                max_profit = prices[i] - min_stock

        return max_profit

For the input [7,1,5,3,6,4] this is returning 0, which I can't figure why to save my life. Wouldn't min be updated eventually to be 1, and then max_profit would be updated to be 6 - min = 6 - 1 = 5?

From what I see, you update max_profit on the condition that prices[i] - 1000000 > max_profit . Since the left hand side will typically end up negative because your prices list holds small values, the max_profit variable will never be updated unless prices[i] is greater than 1000000.

If you're just trying to get the min and max in a list, I would do something like the following, but I am not sure what you are trying to accomplish:

def get_min_max(prices):
    min = 1000000
    max = -1000000
    for p in prices:
        if p > max:
            max = p
        if p < min:
            min = p
    return min, max

I think the problem is that you loop the two calculation together, the result wrong because you put strict constraint in this case. You should separate the loop.

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """

        min_stock = 1000000
        max_profit = 0

        for i in range(len(prices)):
            if prices[i] < min_stock:
                min_stock = prices[i]

        for i in range(len(prices)):

            if prices[i] - min_stock > max_profit:
                max_profit = prices[i] - min_stock

        return max_profit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM