Get a number of possible distinct sub-arrays such that they have at most the given number of odd numbers in it.
Example:
arr = [2,1,2,1,3]
m = 2.
Answer:
10
Explanation:
- Distinct sub arrays with 0 odd numbers = [2]
- Distinct sub arrays with 1 odd numbers = [2,1], [1], [2,1,2], [1,2] and [3]
- Distinct sub arrays with 2 odd numbers = [2,1,2,1], [1,2,1], [2,1,3], [1,3]
So a total of 10 possible distinct sub arrays.
Constraints:
The array size can be up to 1000 elements, m can range from 1 to array size.
public static int process(List<Integer> arr, int m) {
Set<String> set = new LinkedHashSet<>();
for (int i = 0; i < arr.size(); i++) {
for (int j = i; j < arr.size(); j++) {
int odd = 0;
StringBuilder sb = new StringBuilder();
for (int k1 = i; k1 <= j; k1++) {
if (arr.get(k1) % 2 != 0) {
odd++;
}
sb.append(arr.get(k1) + " ");
}
if (odd <= m) {
set.add(sb.toString());
}
}
}
return set.size();
}
This program works for small inputs but as I have 3 for loops it fails for large inputs. What is the correct approach to solve this program?
I have already gone through this post - find number of subarrays with specified number of odd integers but here the questions is not considering about distinct sub arrays.