Given an array arr[] of n integers and an integer K, the task is to find the number of ways to select exactly K even numbers from the given array.
**Examples: **
_Input: __arr[] = {1, 2, 3, 4} k = 1 _
Output:_ 2 _
Explanation:
The number of ways in which we can select one even number is 2.
_Input: _arr[] = {61, 65, 99, 26, 57, 68, 23, 2, 32, 30} k = 2
Output:10
Explanation:
The number of ways in which we can select 2 even number is 10.
Approach: The idea is to apply the rule of combinatorics. For choosing r objects from the given n objects, the total number of ways of choosing is given by nCr. Below are the steps:
Below is the implementation of the above approach:
filter_none
edit
play_arrow
brightness_4
// C++ program for the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
**long**
**long**
f[12];
// Function for calculating factorial
**void**
fact()
{
// Factorial of n defined as:
// n! = n * (n - 1) * ... * 1
f[0] = f[1] = 1;
**for**
(``**int**
i = 2; i <= 10; i++)
f[i] = i * 1LL * f[i - 1];
}
// Function to find the number of ways to
// select exactly K even numbers
// from the given array
**void**
solve(``**int**
arr[],
**int**
n,
**int**
k)
{
fact();
// Count even numbers
**int**
even = 0;
**for**
(``**int**
i = 0; i < n; i++) {
// Check if the current
// number is even
**if**
(arr[i] % 2 == 0)
even++;
}
// Check if the even numbers to be
// choosen is greater than n. Then,
// there is no way to pick it.
**if**
(k > even)
cout << 0 << endl;
**else**
{
// The number of ways will be nCk
cout << f[even] / (f[k] * f[even - k]);
}
}
// Driver Code
**int**
main()
{
// Given array arr[]
**int**
arr[] = { 1, 2, 3, 4 };
**int**
n =
**sizeof**
arr /
**sizeof**
arr[0];
// Given count of even elements
**int**
k = 1;
// Function Call
solve(arr, n, k);
**return**
0;
}
Output:
2
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #combinatorial #dynamic programming #mathematical #combionatrics #permutation and combination #school-programming