-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubArrayIntegerArray.java
More file actions
36 lines (29 loc) · 1.13 KB
/
SubArrayIntegerArray.java
File metadata and controls
36 lines (29 loc) · 1.13 KB
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
33
34
35
36
import java.util.*;
class ArithmeticSubarrays {
public static List<List<Integer>> findArithmeticSubarrays(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 1; i++) {
List<Integer> subarray = new ArrayList<>();
subarray.add(nums[i]);
int diff = nums[i + 1] - nums[i];
// Only proceed if the difference is ±1
if (diff == 1 || diff == -1) {
subarray.add(nums[i + 1]);
// Expand subarray while maintaining the difference
for (int j = i + 2; j < nums.length; j++) {
if (nums[j] - nums[j - 1] == diff) {
subarray.add(nums[j]);
} else {
break; // Stop expansion when condition breaks
}
}
result.add(new ArrayList<>(subarray));
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {3, 4, 5, 7, 8, 9, 10, 12};
System.out.println(findArithmeticSubarrays(nums));
}
}