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