Skip to content

Instantly share code, notes, and snippets.

@rdarder
Created June 26, 2015 17:21
Show Gist options
  • Save rdarder/39df1a0586f7798ab678 to your computer and use it in GitHub Desktop.
Save rdarder/39df1a0586f7798ab678 to your computer and use it in GitHub Desktop.
Max interval sum in go
package main
import "fmt"
import "errors"
type sumTracker []int
func (self sumTracker) add(i, j, amount int) error {
if i > j {
return errors.New("range order")
}
if i < 0 || j >= len(self) {
return errors.New("bounds")
}
if amount < 0 {
return errors.New("amount")
}
self[j] += amount
if i > 0 {
self[i-1] -= amount
}
return nil
}
func (self sumTracker) totals() (totals []int) {
totals = make([]int, len(self))
delta := 0
for i := len(self) - 1; i > 0; i-- {
delta += self[i]
totals[i] = delta
}
return
}
func maxPosValue(totals []int) (maxPos int, maxAmount int) {
for i, amount := range totals {
if amount > maxAmount {
maxPos = i
maxAmount = amount
}
}
return
}
func main() {
tracker := make(sumTracker, 10)
tracker.add(0, 9, 1)
tracker.add(0, 5, 3)
tracker.add(4, 7, 2)
tracker.add(8, 8, 4)
fmt.Printf("deltas: %+v\n", tracker)
totals := tracker.totals()
fmt.Printf("totals: %v\n", totals)
maxPos, maxValue := maxPosValue(totals)
fmt.Printf("max: %v at pos %v\n", maxPos, maxValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment