54 lines
1,013 B
Go
54 lines
1,013 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"cmp"
|
||
|
|
||
|
pq "github.com/emirpasic/gods/v2/queues/priorityqueue"
|
||
|
)
|
||
|
|
||
|
type Element struct {
|
||
|
value int
|
||
|
index int
|
||
|
}
|
||
|
|
||
|
func byValue(l, r Element) int {
|
||
|
return cmp.Compare(l.value, r.value)
|
||
|
}
|
||
|
|
||
|
func byReversedValue(l, r Element) int {
|
||
|
return cmp.Compare(r.value, l.value)
|
||
|
}
|
||
|
|
||
|
func longestSubarray(nums []int, limit int) int {
|
||
|
maxHeap := pq.NewWith(byReversedValue)
|
||
|
minHeap := pq.NewWith(byValue)
|
||
|
|
||
|
longest := 0
|
||
|
|
||
|
left := 0
|
||
|
for right := 0; right < len(nums); right++ {
|
||
|
maxHeap.Enqueue(Element{nums[right], right})
|
||
|
minHeap.Enqueue(Element{nums[right], right})
|
||
|
|
||
|
maxElement, _ := maxHeap.Peek()
|
||
|
minElement, _ := minHeap.Peek()
|
||
|
for maxElement.value-minElement.value > limit {
|
||
|
left = 1 + min(maxElement.index, minElement.index)
|
||
|
|
||
|
for maxElement.index < left {
|
||
|
maxHeap.Dequeue()
|
||
|
maxElement, _ = maxHeap.Peek()
|
||
|
}
|
||
|
|
||
|
for minElement.index < left {
|
||
|
minHeap.Dequeue()
|
||
|
minElement, _ = minHeap.Peek()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
longest = max(longest, right-left+1)
|
||
|
}
|
||
|
|
||
|
return longest
|
||
|
}
|