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:
parent
c15de5ee79
commit
9989455c12
1 changed files with 51 additions and 0 deletions
51
java/continuous-subarrays.java
Normal file
51
java/continuous-subarrays.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue