I want to determine the number of distinct subarrays that can form having at most a given number of odd elements. Two subarrays are distinct if they differ at even one position. The subarray is a contiguous position of an array. Please give some suggestions to improve the time and space complexity.
Exp1:
Input: nums = [1, 2, 3, 4], k = 1
Output: 8
Explanation: [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [2, 3, 4]
Exp2:
Input: nums = [3, 2, 3, 4], k = 1
Output: 7
Explanation: [3], [2], [4], [3, 2], [2, 3], [3, 4], [2, 3, 4]
Note we did not count [3, 2, 3] since it has more than k odd elements.
Exp3:
Input: nums = [3, 2, 3, 2], k = 1
Output: 5
Explanation: [3], [2], [3, 2], [2, 3], [2, 3, 2]
[3], [2], [3, 2] - duplicates
[3, 2, 3], [3, 2, 3, 2] - more than k odd elements
class result {
static int numberOfSubarrays(int[] numbers, int k) {
if(k == 0) return 0;
boolean [] IsOdd = new boolean [numbers.length];
for(int i = 0; i < numbers.length; i++){
IsOdd[i] = numbers[i] %2 != 0;
}
HashSet<String> subs = new HashSet<String>();
for(int i = 0; i < numbers.length; i++){
StringBuilder sb = new StringBuilder();
int oddCount = 0;
for(int j = i; j < numbers.length; j++){
if(IsOdd[j]){
oddCount++;
if(oddCount > k){
break;
}
}
sb.append(numbers[j] + " ");
subs.add(sb.toString());
}
}
return subs.size();
}
}