Best Time To Buy And Sell Stock
Track the lowest buy price in one pass and sell later for the largest gain, so one scan finds the best profit without nested loops.
Code
package main
import "fmt"
// maxProfit: track the lowest buy price seen so far, sell later for max gain
func maxProfit(prices []int) int {
best := 0
lowest := prices[0]
for _, price := range prices[1:] {
if price < lowest {
lowest = price
continue
}
if gain := price - lowest; gain > best {
best = gain
}
}
return best
}
func main() {
fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
fmt.Println(maxProfit([]int{7, 6, 4, 3, 1}))
fmt.Println(maxProfit([]int{2, 4, 1}))
}The code in its own words
The part that carries the load is the functions maxProfit and main — everything else is wiring.
Iteration happens inside for _, price := range prices[1:] — everything outside it runs once.
What to watch for
- Zero packages pulled in — the runtime ships every API this code touches.
Using it
Signature: func maxProfit(prices []int) int
The demo flow inside main is maxProfit — run the file to see it end to end.
Key statements
for _, price := range prices[1:] {
if price < lowest {
lowest = price
continue
}
if gain := price - lowest; gain > best {
best = gain
}
}
func main() {
fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
fmt.Println(maxProfit([]int{7, 6, 4, 3, 1}))
fmt.Println(maxProfit([]int{2, 4, 1}))
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- How do you run Best Time To Buy And Sell Stock?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.