java: add «2762. Continuous Subarrays»

URL:	https://leetcode.com/problems/continuous-subarrays/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-14 22:58:59 +01:00
parent c15de5ee79
commit 9989455c12
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -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;
}
}