From 24735bf4c0c4baa9afcdd6b4638f8e815b4f7977 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 23 Jun 2024 22:17:38 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1438.=20Longest=20Continuous?= =?UTF-8?q?=20Subarray=20With=20Absolute=20Diff=20Less=20Than=20or=20Equal?= =?UTF-8?q?=20to=20Limit=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...solute-diff-less-than-or-equal-to-limit.go | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 go/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.go diff --git a/go/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.go b/go/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.go new file mode 100644 index 0000000..ab16d54 --- /dev/null +++ b/go/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.go @@ -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 +}