Given three positive integers N, L and R. The task is to find the number of ways to form an array of size N where each element lies in the range [L, R] such that the total sum of all the elements of the array is divisible by 2.
Input: N = 2, L = 1, R = 3
Possible arrays having sum of all elements divisible by 2 are
[1, 1], [2, 2], [1, 3], [3, 1] and [3, 3]
Input: N = 3, L = 2, R = 2
Approach: The idea is to find the count of numbers having remainder 0 and 1 modulo 2 separately lying between L and R. This count can be calculated as follows:
We need to count numbers between range having remainder 1 modulo 2
F = First number in range of required type
L = Last number in range of required type
Count = (L – F) / 2
cnt0, and cnt1 represents Count of numbers between range of each type.
Then, using dynamic programming we can solve this problem. Let dp[i][j] denotes the number of ways where the sum of first i numbers modulo 2 is equal to j. Suppose we need to calculate dp[i], then it will have the following recurrence relation: dp[i] = (cnt0 * dp[i – 1] + cnt1 * dp[i – 1]). First term represents the number of ways upto (i – 1) having sum remainder as 0, so we can place cnt0 numbers in ith position such that sum remainder still remains 0. Second term represents the number of ways upto (i – 1) having sum remainder as 1, so we can place cnt1 numbers in ith position to such that sum remainder becomes 0. Similarly, we can calculate for dp[i].
Final answer will be denoted by dp[N].
Below is the implementation of the above approach:
- Number of ways to form a heap with n distinct integers
- Count integers in a range which are divisible by their euler totient value
- Number of ways to form an array with distinct adjacent elements
- Given an array and two integers l and r, find the kth largest element in the range [l, r]
- Count numbers in a range that are divisible by all array elements
- Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
- Total number of ways to place X and Y at n places such that no two X are together
- Different ways to represent N as sum of K non-zero integers
- Ways to write n as sum of two or more positive integers
- Ways to write N as sum of two or more positive integers | Set-2
- Count of sub-sets of size n with total element sum divisible by 3
- Count total divisors of A or B in a given range
- Count ways to express even number ‘n’ as sum of even integers
- Minimum product of k integers in an array of positive Integers
- Total numbers with no repeated digits in a range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.