Why nto brute force as below?
run a loop i=0 to arr.length
within the loop run another loop i to arr.length and compute product as you go and add to the result array. break if product > target
Although both tests pass, it will be more accurate if I sort beforehand.
import java.util.*;
class SubarrayProductLessThanK {
public static List<List> findSubarrays(int[] arr, int target) {
List<List> subarrays = new ArrayList<>();
int right = 0 ; // TODO: Write your code here
int currentProduct = 1;
int left = 0;
for (int i = 0 ; i < arr.length; i++){
left = i;
right = i;
currentProduct = 1;
while (right < arr.length){
currentProduct *= arr[right];
if (currentProduct < target){
ArrayList<Integer> desiredArray = new ArrayList<>();
for (int j = left ; j <=right; j++){
desiredArray.add(arr[j]);
}
subarrays.add(desiredArray);
right++;
}
else{
break;
}
}
}
return subarrays;
}
}
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Subarrays with Product Less than a Target (medium) - Grokking the Coding Interview: Patterns for Coding Questions