The general problem: Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays.
My question:
I want to solve this problem recursively. The part I'm struggling to implement is how do I use the count from every previous recursive call and sum up all the counts, and return one last count like it is shown in the attempt.
Example:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
My attempt:
int helperFunction(vector<int> &nums, int k, int starter, int count)
{
int sum=0;
if (starter >= nums.size())
{
return count;
}
for (int i = starter; i < nums.size(); i++)
{
if (nums[i] % 2 == 1)
{
if (++sum == k)
{
count += nums.size() - i;
sum = 0;
}
}
}
return helperFunction(nums, k, starter + 1, count);
}
int numberOfSubarrays(vector<int> &nums, int k)
{
return helperFunction(nums, k, 0, 0);
}
int main()
{
vector<int> mine;
int myints[] = {1, 1, 2, 1, 1};
mine.assign(myints, myints + 5);
cout << "Output : " << numberOfSubarrays(mine, 3);
return 0;
}
Return Value:
The return value of this actual attempt is 0 means the program is at least not wrong syntactically.
sumif all you do is declare it as indeterminate, bump it once (to something just-as-indeterminate), compare it tok(which means all you're really doing is sayingif (k == <something??>), conditionally resetting it to zero, then letting it scope expire anyway. That var seems utterly unnecessary. At a minimum to be proper, I would expectsumto be initialized, and if it was, it quickly becomes completely pointless.sumshould be declared one block ahead. The point of sum is that once I getkcondition checks I should start counting the sub-arrays, so if a the "minimal" sub-array M verifies it that means every sub-array in this form [M,...] verifies it without even checking