Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subsequences of the given array with average K.
Examples:
Input: arr[] = {9, 7, 8, 9}, K = 8
Output: 5
Explanation: The subsequences having average 8 are {8}, {9, 7}, {7, 9}, {9, 7, 8}, {7, 8, 9}.Input: arr[] = {5, 5, 1}, K = 4
Output: 0
Explanation: No such subsequence can be obtained
Naive Approach: The simplest approach to solve the problem is to use recursion. Follow the steps below to solve the problem:
- Two options are possible for each array element, i.e. either to include the current element in the sum or to exclude the current element in the sum and increase the current index for each recursive call.
- For both the above possibilities, return the number of subsequences with average K.
- The base case is to check if the last index has been reached or not. The average in the base case can be calculated by dividing the sum of array elements included in that subsequence.
- If the average is equal to K, then return 1. Otherwise, return 0.
Time Complexity: O(2N)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized using Dynamic Programming. Follow the steps below to solve the problem:
- Initialize a 3D array, say dp[][][], where dp[i][k][s] is the number of ways to select k integers from the first i integers such that the sum of the selected integers is s.
- Traverse the array.
- Two possible options are available for each element, i.e. either to include it or exclude it.
- If the current element at index i is included, then the next index state will be i + 1 and the count of selected elements will increase from k to k + 1 and the sum s will increase to s + arr[i].
- If the current element at index i is excluded, only index i will increase to i+1 and all the other states will remain the same.
- Below is the dp transition state for this problem:
If ith element is included, then dp[i + 1][k + 1][s + arr[i]] += dp[i][k][s]
If ith element is excluded, then dp[i + 1][k][s] += dp[i][k][s]
- Finally, the answer will be the summation of dp[N][j][K*j] for all j ( 1 ? j ? N.
Below is the implementation of the above approach:
C++14
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Stores the dp statesint dp[101][101][1001];Â
// Function to find the count of// subsequences having average Kint countAverage(int n, int K, int* arr){Â
    // Base condition    dp[0][0][0] = 1;Â
    // Three loops for three states    for (int i = 0; i < n; i++) {        for (int k = 0; k < n; k++) {            for (int s = 0; s <= 1000; s++) {Â
                // Recurrence relation                dp[i + 1][k + 1][s + arr[i]]                    += dp[i][k][s];                dp[i + 1][k][s] += dp[i][k][s];            }        }    }Â
    // Stores the sum of dp[n][j][K*j]    // all possible values of j with    // average K and sum K * j    int cnt = 0;Â
    // Iterate over the range [1, N]    for (int j = 1; j <= n; j++) {        cnt += dp[n][j][K * j];    }Â
    // Return the final count    return cnt;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 9, 7, 8, 9 };Â Â Â Â int K = 8;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << countAverage(N, K, arr);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Stores the dp statesstatic int [][][]dp = new int[101][101][1001];Â
// Function to find the count of// subsequences having average Kstatic int countAverage(int n, int K, int[] arr){Â
    // Base condition    dp[0][0][0] = 1;Â
    // Three loops for three states    for (int i = 0; i < n; i++)     {        for (int k = 0; k < n; k++)         {            for (int s = 0; s <= 100; s++)             {Â
                // Recurrence relation                dp[i + 1][k + 1][s + arr[i]]                    += dp[i][k][s];                dp[i + 1][k][s] += dp[i][k][s];            }        }    }Â
    // Stores the sum of dp[n][j][K*j]    // all possible values of j with    // average K and sum K * j    int cnt = 0;Â
    // Iterate over the range [1, N]    for (int j = 1; j <= n; j++)     {        cnt += dp[n][j][K * j];    }Â
    // Return the final count    return cnt;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int arr[] = { 9, 7, 8, 9 };Â Â Â Â int K = 8;Â Â Â Â int N = arr.length;Â Â Â Â System.out.print(countAverage(N, K, arr));}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python3 program for the above approachÂ
# Stores the dp statesdp = [[[0 for i in range(1001)] for i in range(101)] for i in range(101)]Â
# Function to find the count of# subsequences having average Kdef countAverage(n, K, arr):    global dp    dp[0][0][0] = 1Â
    # Three loops for three states    for i in range(n):        for k in range(n):            for s in range(100):Â
                # Recurrence relation                dp[i + 1][k + 1][s + arr[i]] += dp[i][k][s]                dp[i + 1][k][s] += dp[i][k][s]Â
    # Stores the sum of dp[n][j][K*j]    # all possible values of j with    # average K and sum K * j    cnt = 0Â
    # Iterate over the range [1, N]    for j in range(1, n + 1):        cnt += dp[n][j][K * j]Â
    # Return the final count    return cntÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â arr= [9, 7, 8, 9]Â Â Â Â K = 8Â Â Â Â N = len(arr)Â
    print(countAverage(N, K, arr))Â
    # This code is contributed by mohit kumar 29. |
C#
// C# program for the above approachusing System;public class GFG{Â
// Stores the dp statesstatic int [,,]dp = new int[101, 101, 1001];Â
// Function to find the count of// subsequences having average Kstatic int countAverage(int n, int K, int[] arr){Â
    // Base condition    dp[0, 0, 0] = 1;Â
    // Three loops for three states    for (int i = 0; i < n; i++)     {        for (int k = 0; k < n; k++)         {            for (int s = 0; s <= 100; s++)             {Â
                // Recurrence relation                dp[i + 1, k + 1, s + arr[i]]                    += dp[i, k, s];                dp[i + 1, k, s] += dp[i, k, s];            }        }    }Â
    // Stores the sum of dp[n,j,K*j]    // all possible values of j with    // average K and sum K * j    int cnt = 0;Â
    // Iterate over the range [1, N]    for (int j = 1; j <= n; j++)     {        cnt += dp[n, j, K * j];    }Â
    // Return the readonly count    return cnt;}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int []arr = { 9, 7, 8, 9 };Â Â Â Â int K = 8;Â Â Â Â int N = arr.Length;Â Â Â Â Console.Write(countAverage(N, K, arr));}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Stores the dp statesvar dp = Array.from(Array(101), ()=> Array(101));Â
for(var i =0; i<101; i++)Â Â Â Â Â Â Â Â for(var j =0; j<101; j++)Â Â Â Â Â Â Â Â Â Â Â Â dp[i][j] = new Array(1001).fill(0); Â
Â
// Function to find the count of// subsequences having average Kfunction countAverage(n, K, arr){Â
    // Base condition    dp[0][0][0] = 1;Â
    // Three loops for three states    for (var i = 0; i < n; i++) {        for (var k = 0; k < n; k++) {            for (var s = 0; s <= 1000; s++) {Â
                // Recurrence relation                dp[i + 1][k + 1][s + arr[i]]                    += dp[i][k][s];                dp[i + 1][k][s] += dp[i][k][s];            }        }    }Â
    // Stores the sum of dp[n][j][K*j]    // all possible values of j with    // average K and sum K * j    var cnt = 0;Â
    // Iterate over the range [1, N]    for (var j = 1; j <= n; j++) {        cnt += dp[n][j][K * j];    }Â
    // Return the final count    return cnt;}Â
// Driver Codevar arr = [9, 7, 8, 9];var K = 8;var N = arr.lengthdocument.write( countAverage(N, K, arr));Â
</script> |
5
Time Complexity: O(S*N2) where S is the sum of the array.
Auxiliary Space: O(S*N2)Â
Efficient approach : Space optimization
In previous approach the current value dp[i][j][s] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 2D array to store the computations.
Implementation:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the count of// subsequences having average Kint countAverage(int n, int K, int* arr){    // Initialize a 2D array with 0's    int dp[101][1001] = {0};Â
    // Base condition    dp[0][0] = 1;Â
    // Three loops for three states    for (int i = 0; i < n; i++) {        for (int k = n; k > 0; k--) {            for (int s = 1000; s >= arr[i]; s--) {Â
                // Recurrence relation                dp[k][s] += dp[k - 1][s - arr[i]];            }        }    }Â
    // Stores the sum of dp[n][K*j]    // for all possible values of j    int cnt = 0;Â
    // Iterate over the range [1, N]    for (int j = 1; j <= n; j++) {        cnt += dp[j][K * j];    }Â
    // Return the final count    return cnt;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 9, 7, 8, 9 };Â Â Â Â int K = 8;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << countAverage(N, K, arr);Â
    return 0;} |
Java
public class CountAverageSubsequences {Â
    // Function to find the count of subsequences having    // average K    static int countAverage(int n, int K, int[] arr)    {        // Initialize a 2D array with 0's        int[][] dp = new int[101][1001];Â
        // Base condition        dp[0][0] = 1;Â
        // Three loops for three states        for (int i = 0; i < n; i++) {            for (int k = n; k > 0; k--) {                for (int s = 1000; s >= arr[i]; s--) {Â
                    // Recurrence relation                    dp[k][s] += dp[k - 1][s - arr[i]];                }            }        }Â
        // Stores the sum of dp[n][K*j] for all possible        // values of j        int cnt = 0;Â
        // Iterate over the range [1, N]        for (int j = 1; j <= n; j++) {            cnt += dp[j][K * j];        }Â
        // Return the final count        return cnt;    }Â
    // Main method    public static void main(String[] args)    {        int[] arr = { 9, 7, 8, 9 };        int K = 8;        int N = arr.length;        System.out.println(countAverage(N, K, arr));    }} |
Python
def count_average(n, K, arr):    # Initialize a 2D list with 0's    dp = [[0 for _ in range(1001)] for _ in range(101)]Â
    # Base condition    dp[0][0] = 1Â
    # Three loops for three states    for i in range(n):        for k in range(n, 0, -1):            for s in range(1000, arr[i] - 1, -1):Â
                # Recurrence relation                dp[k][s] += dp[k - 1][s - arr[i]]Â
    # Stores the sum of dp[n][K*j]    # for all possible values of j    cnt = 0Â
    # Iterate over the range [1, N]    for j in range(1, n + 1):        cnt += dp[j][K * j]Â
    # Return the final count    return cntÂ
# Driver CodeÂ
Â
def main():Â Â Â Â arr = [9, 7, 8, 9]Â Â Â Â K = 8Â Â Â Â N = len(arr)Â Â Â Â print(count_average(N, K, arr))Â
Â
if __name__ == "__main__":Â Â Â Â main() |
C#
using System;Â
class GFG {  // Function to find the count of // subsequences having average K    static int CountAverage(int n, int K, int[] arr)    {        // Initialize a 2D array with 0's        int[, ] dp = new int[101, 1001];Â
        // Base condition        dp[0, 0] = 1;Â
        // Three loops for three states        for (int i = 0; i < n; i++) {            for (int k = n; k > 0; k--) {                for (int s = 1000; s >= arr[i]; s--) {                    // Recurrence relation                    dp[k, s] += dp[k - 1, s - arr[i]];                }            }        }Â
        // Stores the sum of dp[n][K*j]        // for all possible values of j        int cnt = 0;Â
        // Iterate over the range [1, N]        for (int j = 1; j <= n; j++) {            cnt += dp[j, K * j];        }Â
        // Return the final count        return cnt;    }Â
    static void Main(string[] args)    {        int[] arr = { 9, 7, 8, 9 };        int K = 8;        int N = arr.Length;        Console.WriteLine(CountAverage(N, K, arr));    }} |
Javascript
function countAverage(N, K, arr) {    // Initialize a 2D array with 0's    const dp = new Array(101);    for (let i = 0; i <= 100; i++) {        dp[i] = new Array(1001).fill(0);    }Â
    // Base condition    dp[0][0] = 1;Â
    // Three loops for three states    for (let i = 0; i < N; i++) {        for (let k = N; k > 0; k--) {            for (let s = 1000; s >= arr[i]; s--) {                // Recurrence relation                dp[k][s] += dp[k - 1][s - arr[i]];            }        }    }Â
    // Stores the sum of dp[N][K*j]    // for all possible values of j    let cnt = 0;Â
    // Iterate over the range [1, N]    for (let j = 1; j <= N; j++) {        cnt += dp[j][K * j];    }Â
    // Return the final count    return cnt;}Â
// Driver Codeconst arr = [9, 7, 8, 9];const K = 8;const N = arr.length;console.log(countAverage(N, K, arr)); |
5
Time Complexity: O(S*N2) where S is the sum of the array.
Auxiliary Space: O(S*N)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
