Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình tìm lợi nhuận tối đa mua bán cổ phiếu một lần trong Python


Cho danh sách prices giá cổ phiếu theo thời gian. Tìm lợi nhuận tối đa từ việc mua và bán chỉ một lần. Phải mua trước khi bán.

Ví dụ, prices = [10, 12, 9, 6, 8, 12], đầu ra là 6, vì mua ở 6 bán ở 12.

Các bước giải quyết:

  • max_profit := 0.
  • min_stock := infinity.
  • Duyệt từng price trong prices:
    • max_profit = max(max_profit, price - min_stock).
    • min_stock = min(min_stock, price).
  • Trả về max_profit.

Ví dụ minh họa

class Solution:
    def solve(self, prices):
        max_profit = 0
        min_stock = float('inf')
        for price in prices:
            max_profit = max(max_profit, price - min_stock)
            min_stock = min(min_stock, price)
        return max_profit

ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))

Đầu vào

[10, 12, 9, 6, 8, 12]

Đầu ra

6