// This example demonstrates a priority queue built using the heap interface.
package main
import (
"container/heap"
"fmt"
)
// An Item is something we manage in a priority queue.
type Item struct {
value int // The value of the item; arbitrary.
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq[i].value > pq[j].value
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = j
pq[j].index = i
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value int, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
func main() {
nums := []int{1, 3, 2, -3, 5, 3, 6, 7, 8, 9}
k := 3
result := maxSlidingWindow(nums, k)
fmt.Println("result", result)
}
func maxSlidingWindow(nums []int, k int) {
pq := make(PriorityQueue, len(nums))
res := []int{}
for i := 0; i < k; i++ {
pq[i] = &Item{
value: nums[i],
priority: nums[i],
index: i,
}
res = append(res, nums[i])
}
heap.Init(&pq)
peek := pq[0]
fmt.Println(peek.value) // its a maxheap and gives the largest element
temp := heap.Pop(&pq).(*Item)
fmt.Println("temp:", temp)
remove := heap.Remove(&pq, 0).(*Item)
// pq = slices.Delete(pq, 5)
fmt.Println("remove:", remove)
for i:=0;i<len(nums);i++{
//remove the desired element from the priority Queue
// insert the next element in the Priority queue
// peek the highest value
}
}
I am trying to print the maximum value in a sliding window. Putting the elements of window size, here k = 3 into the priority queue(Maxheap) and then peek the value. "heap.Init(&pq)" will assign the index in pq based on the priority. Look for maxSlidingWindow function, the last for loop prints the max element for each window of size k. If you compare the indices in the pq and the nums array the indices will be different. And hence deleting the desired element from the priority queue seems almost impossible.