121. The best time to buy and sell stocks leetcode

Description of the problem

Given an array, which i-th element is a given stock i-day prices.

If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.

Note that you can not sell the stock before buying stocks.

Example 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

Example 2

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0

Solution 1- Violence Act

Do two for loops
Here Insert Picture Description

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit=0
        for i in range(len(prices)):
            for j in range(i):
                max_profit=max(max_profit,prices[i]-prices[j])
        return max_profit

Violence overtime
Here Insert Picture Description

Once traversal solution 2-

After reading method is to write their own solution to a problem, some do not understand the original solution was added subsequent understanding, adding to sell the i-th day, then the maximum profit must be in [0, i-1] option to buy the lowest point in between, so through the array , sequentially obtains each difference selling point of time, selecting the maximum value
Here Insert Picture Description

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if prices==[]:
            return 0
        else:
            min_price=prices[0]
            max_profit=0
            for i in range(len(prices)):
                min_price=min(min_price,prices[i])
                max_profit=max(max_profit,prices[i]-min_price)            
            return max_profit
Published 284 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_39289876/article/details/104762509