121. Best Time to Buy and Sell Stock

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

C#

public class Solution
{
    public int MaxProfit(int[] prices)
    {
        if (prices.Length <= 1) return 0;
        int lowestPrice = prices[0];
        int highestProfit = 0;
        foreach(int price in prices)
        {
            lowestPrice = Math.Min(lowestPrice, price);
            highestProfit = Math.Max(highestProfit, price - lowestPrice);
        }

        return highestProfit;
    }
}

We set a guard clause to catch arrays of length 1 or less. Initialize the first price to be the lowest price. Loop through the array, updating the lowest price and the highest profit thus far. Return the highest profit.

Design a site like this with WordPress.com
Get started