problem_solving_10.py 649 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
"""
买卖股票的最佳时机
"""
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        """
        贪心算法
        2个变量,一个最小价格,一个最大利润
        :param prices:
        :return:
        """
        min_price = prices[0]
        max_profit = 0
        for i in range(1, len(prices)):
            if prices[i] < min_price:
                min_price = prices[i]
            else:
                max_profit = max(max_profit, prices[i] - min_price)
        return max_profit


if __name__ == '__main__':
    root = Solution().maxProfit([7, 1, 5, 3, 6, 4])
    print(root)