Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Best Time to Buy and Sell Stock

C++, Python and TypeScript solutions for Best Time to Buy and Sell Stock.

The Best Time to Buy and Sell Stock solutions are below.

Solution files

Python•best-time-to-buy-and-sell-stock/synced-solution.py
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float('inf')
        max_profit = 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 = 0;
        for (int price : prices) {
            min_price = min(min_price, price);
            max_profit = max(max_profit, price - min_price);
        }
        return max_profit;
    }
};
TypeScript•best-time-to-buy-and-sell-stock/synced-solution.ts
function maxProfit(prices: number[]): number {
    let min_price = Infinity;
    let max_profit = 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;
}