15 Jun 2024C++ / Python / TypeScriptEasy

Best Time to Buy and Sell Stock

Collected C++, Python, TypeScript solutions for best time to buy and sell stock. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Best Time to Buy and Sell Stock. the solution files are available below.

solution files

  • C++ best-time-to-buy-and-sell-stock/synced-solution.cpp
  • Python best-time-to-buy-and-sell-stock/synced-solution.py
  • TypeScript best-time-to-buy-and-sell-stock/synced-solution.ts

Solution files

Pythonbest-time-to-buy-and-sell-stock/synced-solution.py
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float(class="syntax-string">'inf')
        max_profit = class="syntax-number">0
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit
C++best-time-to-buy-and-sell-stock/synced-solution.cpp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_price = INT_MAX;
        int max_profit = class="syntax-number">0;
        for (int price : prices) {
            min_price = min(min_price, price);
            max_profit = max(max_profit, price - min_price);
        }
        return max_profit;
    }
};
TypeScriptbest-time-to-buy-and-sell-stock/synced-solution.ts
function maxProfit(prices: number[]): number {
    let min_price = Infinity;
    let max_profit = class="syntax-number">0;
    for (const price of prices) {
        min_price = Math.min(min_price, price);
        max_profit = Math.max(max_profit, price - min_price);
    }
    return max_profit;
}