go: add «1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-06-23 22:17:38 +02:00
parent c87d176475
commit 24735bf4c0
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,53 @@
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
}