Given a range [low, high], both inclusive, and an integer K, the task is to select K numbers from the range(a number can be chosen multiple times) such that the sum of those K numbers is even. Print the number of all such permutations.
Examples:
Input:_ low = 4, high = 5, k = 3_
Output:_ 4_
Explanation:
There are 4 valid permutation. They are {4, 4, 4}, {4, 5, 5}, {5, 4, 5} and {5, 5, 4} which sum up to an even number.
Input:_ low = 1, high = 10, k = 2_
Output:_ 50_
Explanation:
There are 50 valid permutations. They are {1, 1}, {1, 3}, … {1, 9} {2, 2}, {2, 4}, …, {2, 10}, …, {10, 2}, {10, 4}, … {10, 10}.
These 50 permutations, each sum up to an even number.
Naive Approach: The idea is to find all subset of size K such that the sum of the subset is even and also calculate permutation for each required subset.
Time Complexity:_ O(K * (2K))_
Auxiliary Space:_ O(K)_
Efficient Approach: The idea is to use the fact that the sum of two even and odd numbers is always even. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
// Java program for the above approach
**import**
java.util.*;
**class**
GFG {
// Function to return the number
// of all permutations such that
// sum of K numbers in range is even
**public**
**static**
**void**
countEvenSum(``**int**
low,
**int**
high,
**int**
k)
{
// Find total count of even and
// odd number in given range
**int**
even_count = high /
2
- (low -
1``) /
2``;
**int**
odd_count = (high +
1``) /
2
- low /
2``;
**long**
even_sum =
1``;
**long**
odd_sum =
0``;
// Iterate loop k times and update
// even_sum & odd_sum using
// previous values
**for**
(``**int**
i =
0``; i < k; i++) {
// Update the prev_even and
// odd_sum
**long**
prev_even = even_sum;
**long**
prev_odd = odd_sum;
// Even sum
even_sum = (prev_even * even_count)
+ (prev_odd * odd_count);
// Odd sum
odd_sum = (prev_even * odd_count)
+ (prev_odd * even_count);
}
// Return even_sum
System.out.println(even_sum);
}
// Driver Code
**public**
**static**
**void**
main(String[] args)
{
// Given ranges
**int**
low =
4``;
**int**
high =
5``;
// Length of permutation
**int**
K =
3``;
// Function call
countEvenSum(low, high, K);
}
}
Output:
4
Time Complexity:_ O(K)_
Auxiliary Space:_ O(1)_
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 #dynamic programming #greedy #mathematical #adobe #array-range-queries #permutation #permutation and combination