Skip to content

Instantly share code, notes, and snippets.

@a10y
Created May 18, 2016 19:39
Show Gist options
  • Select an option

  • Save a10y/7733855e390046923168b644693544cc to your computer and use it in GitHub Desktop.

Select an option

Save a10y/7733855e390046923168b644693544cc to your computer and use it in GitHub Desktop.
// Solution to the interview question of finding ideal purchase/sale times and profits for
// a history of a single stock, in Go
package main
import "fmt"
// Finds the maximum profit to be had from buying and selling at a given price
func MaxProfit(prices []int) (buy int, sell int, profit int) {
profit = 0
buy = 0
sell = 0
currbuy := 0
for i, _ := range prices {
if i == 0 {
continue // skip first index
}
buyPrice := prices[currbuy]
currPrice := prices[i]
if currPrice < buyPrice {
currbuy = i
} else {
// On new better profit, update the tracker for when we buy, sell and the profit
potentialProfit := currPrice - buyPrice
if potentialProfit > profit {
profit = potentialProfit
buy = currbuy
sell = i
}
}
}
return
}
func main() {
prices := []int{5, 6, 7, 3, 5, 9, 0, 10, -1, 12}
buy, sell, profit := MaxProfit(prices)
fmt.Printf("buy %v, sell %v, profit %v\n", buy, sell, profit) // => 7
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment