Leetcode # 121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Solution

Python 版

class Solution:
  def maxProfit(self, prices: List[int]) -> int:
    min_price = float("inf")
    max_profit = 0
    for price in prices:
      min_price = min(price, min_price)
      max_profit = max(price - min_price, max_profit)

    return max_profit;

C++ 版

class Solution {
public:
  int maxProfit(vector<int>& prices) {
    int min_price = prices[0];
    int max_profit = 0;
    for(int i = 1; i < prices.size(); i++){
      min_price = std::min(prices[i], min_price);
      max_profit = std::max(prices[i] - min_price, max_profit);
    }
    return max_profit;      
  }
};

 

Last Updated on 2023/08/16 by A1go

目錄
Bitnami