Given a binary array arr[] of dimension N, and an integer Okay, the duty is to calculate the variety of methods to partition the array into non-overlapping subarrays, the place every subarray has precisely Okay quantity 0s.
Examples:
Enter: arr[] = [ 0, 0, 1, 1, 0, 1, 0], Okay = 2
Output: 3
Rationalization: Completely different doable partitions are:
{{0, 0}, {1, 1, 0, 1, 0}}, {{0, 0, 1}, {1, 0, 1, 0}}, {{0, 0, 1, 1}, {0, 1, 0}}. So, the output shall be 3.Enter: arr[] = {0, 0, 1, 0, 1, 0}, Okay = 2
Output: 2Enter: arr[] = [1, 0, 1, 1], Okay = 2
Output: 0
Strategy: The strategy to unravel the issue is predicated on the next thought:
If jth 0 is the final 0 for a subarray and (j+1)th 0 is the primary 0 of one other subarray, then the doable variety of methods to partition into these two subarrays is another than the variety of 1s in between jth and (j+1)th 0.
From the above statement, it may be mentioned that the entire doable methods to partition the subarray is the multiplication of the depend of 1s between Okay*x th and (Okay*x + 1)th 0, for all doable x such that Okay*x doesn’t exceed the entire depend of 0s within the array.
Comply with the illustration beneath for a greater understanding of the issue,
Illustration:
Contemplate array arr[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0}, Okay = 2
Index of 2nd 0 and third 0 are 1 and 4
=> Complete variety of 1s in between = 2.
=> Potential partition with these 0s = 2 + 1 = 3.
=> Complete doable partitions until now = 3Index of 4th 0 and fifth 0 are 6 and eight
=> Complete variety of 1s in between = 1.
=> Potential partition with these 0s = 1 + 1 = 2.
=> Complete doable partitions until now = 3*2 = 6The doable partitions are 6:
{{0, 0}, {1, 1, 0, 1, 0}, {1, 0, 0}}, {{0, 0}, {1, 1, 0, 1, 0, 1}, {0, 0}},
{{0, 0, 1}, {1, 0, 1, 0}, {1, 0, 0}}, {{0, 0, 1}, {1, 0, 1, 0, 1}, {0, 0}},
{{0, 0, 1, 1}, {0, 1, 0}, {1, 0, 0}}, {{0, 0, 1, 1}, {0, 1, 0, 1}, {0, 0}}
Comply with the steps talked about beneath to unravel the issue:
- Initialize a counter variable to 1(claiming there exists not less than one such doable manner).
- If there are lower than Okay 0s or variety of 0s is just not divisible by Okay, then such partition is just not doable.
- Then, for each doable (Okay*x)th and (Okay*x + 1)th variety of 0, calculate the variety of doable partitions utilizing the above statement and multiply that with the counter variable to get the entire doable partitions.
- Return the worth of the counter variable.
Right here is the code for the above strategy:
C++
|
Time Complexity: O(N)
Auxiliary House: O(N)