Best Time to Buy and Sell Stock

July 23, 2025

Question

You are given an array prices where prices[i] is the price of a stock on day i. You want to buy one share and sell it later. Return the maximum profit you can get.

If no profit can be made, return 0.

Example

Input: prices = [7, 2, 3, 4, 9, 1]

Output: 7

Explanation: Buy on day 1 (price = 1) and sell on day 4 (price = 9), profit = 9 - 2 = 7.

My Notes

package main

import (
    "fmt"
)

func maxProfit(prices []int) int {
    minPrice := prices[0]
    maxProfit := 0

    for _, price := range prices[1:] {
        if price < minPrice {
            minPrice = price
            continue
        }

        if price-minPrice > maxProfit {
            maxProfit = price - minPrice
        }
    }

    return maxProfit
}

func main() {
    result := maxProfit([]int{7, 2, 3, 4, 9, 1})
    fmt.Println(result)
}