Best Time to Buy and Sell Stock - Leetcode 121

Best Time to Buy and Sell Stock - Leetcode 121

Problem - Leetcode

You are given an array prices where prices[i] is the price of a given stock on the i<sup>th</sup> day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.


  • 1 <= prices.length <= 10<sup>5</sup>

  • 0 <= prices[i] <= 10<sup>4</sup>

Answer-1 in Golang

func maxProfit(prices []int) int {
    min := math.MaxUint32
    res := 0

    for _, price := range prices {
        if price > min {
            if price-min > res {
                res = price - min
        } else {
            min = price
    return res

This code defines a function called maxProfit that takes a slice of integers called prices as its input and returns an integer value representing the maximum profit that can be obtained by buying and selling stocks based on the given prices.

Let's break down the code step by step:

  1. The function starts by declaring two variables: min and res.

    • min is initialized with the maximum value representable by an unsigned 32-bit integer (this is set to a high value to ensure that any price value encountered will be smaller).

    • res is initialized to 0, which will store the maximum profit.

  2. The function then enters a loop using a range-based iteration over the prices slice. In each iteration, it processes one price value from the slice.

  3. Inside the loop, there's an if statement that checks whether the current price is greater than the current min value. This comparison is used to determine if the current price might lead to a potential profit.

  4. If the price is indeed greater than min, it means there's a possibility of making a profit by selling at the current price. The code enters a nested if block.

  5. Within the nested if block, the code calculates the potential profit that could be obtained by selling at the current price minus the min price encountered so far. If this potential profit is greater than the current res (maximum profit recorded so far), it updates res with the new potential profit. This is done to ensure that res holds the maximum profit achievable throughout the iteration.

  6. If the price is not greater than min, it means the current price might be a better candidate for the minimum price to buy at. In this case, the min value is updated to the current price.

  7. After the loop completes, the function returns the final value of res, which represents the maximum profit that can be obtained by buying and selling stocks based on the given prices.

In summary, this code is an implementation of the "buy low, sell high" strategy for maximizing profit in stock trading. It iterates through the prices array, keeping track of the minimum price encountered so far (min) and updating the maximum profit (res) that can be obtained. The key idea is to find the largest price difference between a minimum and a subsequent maximum price in the array.

Did you find this article valuable?

Support Jyotirmoy Barman by becoming a sponsor. Any amount is appreciated!