-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathProblem_4_Longest_Continuous_SubArray.java
32 lines (25 loc) · 1.11 KB
/
Problem_4_Longest_Continuous_SubArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package Ordered_Set;
// Problem Statement: Longest Continuous Subarray (medium)
// LeetCode Question: 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
import java.util.TreeMap;
public class Problem_4_Longest_Continuous_SubArray {
// Function to find the longest subarray with absolute diff less than or equal to limit
public static int longestSubarray(int[] nums, int limit) {
TreeMap<Integer, Integer> map = new TreeMap<>();
int left = 0, maxLength = 0;
for (int right = 0; right < nums.length; right++) {
map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);
// Contract the window if the condition is violated
while (map.lastKey() - map.firstKey() > limit) {
map.put(nums[left], map.get(nums[left]) - 1);
if (map.get(nums[left]) == 0) {
map.remove(nums[left]);
}
left++;
}
// Update the maximum length
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}