-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubarrayProductLessThanK.java
More file actions
31 lines (28 loc) · 1.27 KB
/
SubarrayProductLessThanK.java
File metadata and controls
31 lines (28 loc) · 1.27 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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class SubarrayProductLessThanK {
public static List<List<Integer>> findSubarrays(int[] arr, int target) {
List<List<Integer>> result = new ArrayList<>();
double product = 1;
int left = 0;
for (int right = 0; right < arr.length; right++) {
product *= arr[right];
while (product >= target && left <= right)
product /= arr[left++];
// since the product of all numbers from left to right is less than the target therefore,
// all subarrays from left to right will have a product less than the target too; to avoid
// duplicates, we will start with a subarray containing only arr[right] and then extend it
List<Integer> tempList = new LinkedList<>();
for (int i = right; i >= left; i--) {
tempList.add(0, arr[i]);
result.add(new ArrayList<>(tempList));
}
}
return result;
}
public static void main(String[] args) {
System.out.println(SubarrayProductLessThanK.findSubarrays(new int[] { 2, 5, 3, 10 }, 30));
System.out.println(SubarrayProductLessThanK.findSubarrays(new int[] { 8, 2, 6, 5 }, 50));
}
}