Daily power button a problem

Title forces buckle (the best time to buy and sell stocks) one question per day March 9

I believe that many students in the brush power button, This question is required today is as follows:
Given an array, which i-th element is the price of a given stock i-th day.

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 , you can not sell the stock before buying stocks.
Firstly, the meaning of the questions, given an array, meaning it is an integer type unordered list, the list has an index, can be iterative, can traverse the characteristics of an element represents a day, buying and selling can be only one day of action be one of them, that can only buy or sell, not buy and sell on the same day, to buy or sell.
Note that this requires a good note, the assumption that a given array is [11,6,4,8,], you can not buy after selling ,, that is, buy and sell is not enough, now it requires seeking maximum profit, then the maximum profit no matter how to buy or how to sell, due to the sale and purchase limit does not work, then the difference between the maximum and minimum values of the list must be the maximum profit, minimum is fixed, there is no fixed maximum, because the former can not buy and sell, also that is the maximum value of the index is greater than the minimum value of the index, this is the right time to maximize profits. That is the maximum minus minimum is the maximum difference is profit, but can not buy and sell, so if the maximum value of the index is less than the minimum value index, you need to compare the maximum and minimum times, if the conditions are still not satisfied, the index is less than the minimum, the maximum and minimum out a subtraction, in line with the index value is greater than the minimum until, when the difference between the number to a maximum profit, directly on the following code:

def maxProfit(prices) -> int:
    n = len(prices)
    if n == 0 or n == 1:
        return 0
    min_price = prices[0]
    profit = 0
    for i in range(1, n):
        if prices[i] < min_price:
            min_price = prices[i]
        if prices[i] - min_price > profit:
            profit = prices[i] - min_price
    return profit
print(maxProfit([11,6,4,8]))
至此,本题解答完毕!!
Published 13 original articles · won praise 0 · Views 304

Guess you like

Origin blog.csdn.net/alwaysbefine/article/details/104760186
Recommended