From 9989455c12fe2146b15c45d891c6bf0247c2d248 Mon Sep 17 00:00:00 2001
From: Matej Focko <me@mfocko.xyz>
Date: Sat, 14 Dec 2024 22:58:59 +0100
Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2762.=20Continuous=20Subarr?=
 =?UTF-8?q?ays=C2=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

URL:	https://leetcode.com/problems/continuous-subarrays/
Signed-off-by: Matej Focko <me@mfocko.xyz>
---
 java/continuous-subarrays.java | 51 ++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
 create mode 100644 java/continuous-subarrays.java

diff --git a/java/continuous-subarrays.java b/java/continuous-subarrays.java
new file mode 100644
index 0000000..c29e855
--- /dev/null
+++ b/java/continuous-subarrays.java
@@ -0,0 +1,51 @@
+class Solution {
+  private int i, j;
+  private int runningMin, runningMax;
+
+  private long subarraysInRange() {
+    long length = j - i;
+    return (length * (length + 1)) / 2;
+  }
+
+  private long check(int[] nums) {
+    runningMin = Math.min(runningMin, nums[j]);
+    runningMax = Math.max(runningMax, nums[j]);
+    if (runningMax - runningMin <= 2) {
+      // differences are satisfied, can continue
+      return 0l;
+    }
+
+    long total = subarraysInRange();
+
+    i = j;
+    runningMin = runningMax = nums[j];
+
+    while (i > 0 && Math.abs(nums[j] - nums[i - 1]) <= 2) {
+      --i;
+      runningMin = Math.min(runningMin, nums[i]);
+      runningMax = Math.max(runningMax, nums[i]);
+    }
+
+    // subtract duplicitous count
+    if (i < j) {
+      total -= subarraysInRange();
+    }
+
+    return total;
+  }
+
+  public long continuousSubarrays(int[] nums) {
+    long total = 0;
+
+    i = 0;
+    runningMin = runningMax = nums[i];
+    for (j = 0; j < nums.length; ++j) {
+      total += check(nums);
+    }
+
+    // count final subarrays
+    total += subarraysInRange();
+
+    return total;
+  }
+}