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
- Keep track of the minimum price seen so far while looping.
- On each day, check if selling today (current price - min price) gives a better profit.
- Update the maximum profit if it's better than previous value.
- 🔁 One pass, constant space.
- 🧠 Intuition: Track lowest valley (buy) and highest peak (sell after it).
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) }