Last active
January 17, 2022 16:46
-
-
Save CollinShoop/ea077010d81224b6514d32b238da87be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func maxProduct(nums []int) int { | |
h := NewIntHeap(2, 2, true) | |
for _, num := range nums { | |
heap.Push(h, num) | |
h.Prune() | |
} | |
return (heap.Pop(h).(int)-1) * (heap.Pop(h).(int)-1) | |
} | |
func NewIntHeap(initialSize int, maxSize int, desc bool) *IntHeap { | |
return &IntHeap{ | |
data: make([]int, initialSize)[0:0], | |
desc: desc, | |
maxSize: maxSize, | |
} | |
} | |
type IntHeap struct { | |
data []int | |
desc bool // true = descending, false = ascending | |
initialSize int | |
maxSize int | |
} | |
func (h *IntHeap) resetData() { | |
h.data = make([]int, h.initialSize)[0:0] | |
heap.Init(h) | |
} | |
func (h IntHeap) Len() int { | |
return len(h.data) | |
} | |
func (h IntHeap) Less(i, j int) bool { | |
if h.desc { | |
return h.data[i] > h.data[j] | |
} | |
return h.data[i] < h.data[j] | |
} | |
func (h IntHeap) Swap(i, j int) { | |
h.data[i], h.data[j] = h.data[j], h.data[i] | |
} | |
func (h *IntHeap) Push(x interface{}) { | |
h.data = append(h.data, x.(int)) | |
} | |
func (h *IntHeap) Prune() { | |
if h.maxSize == 0 || h.Len() < h.maxSize { | |
return | |
} | |
// pop the desired values | |
r := make([]int, h.maxSize) | |
for i := 0; i < h.maxSize; i++ { | |
r[i] = heap.Pop(h).(int) | |
} | |
// reset heap data | |
h.resetData() | |
// push back | |
for _, v := range r { | |
heap.Push(h, v) | |
} | |
} | |
func (h *IntHeap) Pop() interface{} { | |
old := *h | |
n := len(old.data) | |
x := old.data[n-1] | |
h.data = old.data[0:n-1] | |
return x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment