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.

GoData Integrity

Code

snippet
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

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.