mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
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:
parent
c87d176475
commit
24735bf4c0
1 changed files with 53 additions and 0 deletions
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue