Count of subsequences with sum two less than the array sum
Last Updated :
12 Dec, 2021
Given an array vec[] of size N of non-negative integers. The task is to count the number of subsequences with the sum equal to S - 2 where S is the sum of all the elements of the array.
Examples:
Input: vec[] = {2, 0, 1, 2, 1}, N=5
Output: 6
Explanation: {2, 0, 1, 1}, {2, 1, 1}, {2, 0, 2}, {2, 2}, {0, 1, 2, 1}, {1, 2, 1}
Input: vec[] = {2, 0, 2, 3, 1}, N=5
Output: 4
Explanation: {2, 0, 3, 1}, {2, 3, 1}, {0, 2, 3, 1}, {2, 3, 1}
Naive Approach: The idea is to generate all subsequences and check the sum of each and every individual subsequence equals S-2 or not.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the total number
// of subsequences with sum S-2
void countTotal(vector<int>& vec)
{
// Calculating vector sum using
// accumulate function
int sum = accumulate(vec.begin(),
vec.end(), 0LL);
int N = (int)vec.size();
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
// Bitmasking technique to generate
// all possible subsequences
for (int mask = 0; mask < (1 << N); mask++) {
// Variable curr counts the
// sum of the current subsequence
int curr = 0;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) != 0) {
// Include ith element
// of the vector
curr += vec[i];
}
}
if (curr == sum - 2)
answer++;
}
// Print the answer
cout << answer;
}
// Driver Code
int main()
{
// Initializing a vector
vector<int> vec = { 2, 0, 1, 2, 1 };
countTotal(vec);
return 0;
}
Java
// Java program for the above approach
public class GFG {
static int accumulate(int [] vec){
int sum1 = 0;
for (int i = 0; i < vec.length; i++)
sum1 += vec[i];
return sum1;
}
// Function to count the total number
// of subsequences with sum S-2
static void countTotal(int []vec)
{
// Calculating vector sum using
// accumulate function
int sum = accumulate(vec);
int N = vec.length;
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
// Bitmasking technique to generate
// all possible subsequences
for (int mask = 0; mask < (1 << N); mask++) {
// Variable curr counts the
// sum of the current subsequence
int curr = 0;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) != 0) {
// Include ith element
// of the vector
curr += vec[i];
}
}
if (curr == sum - 2)
answer++;
}
// Print the answer
System.out.print(answer);
}
// Driver Code
public static void main (String[] args)
{
// Initializing a vector
int []vec = { 2, 0, 1, 2, 1 };
countTotal(vec);
}
}
// This code is contributed by AnkThon
Python3
# python3 program for the above approach
# Function to count the total number
# of subsequences with sum S-2
def countTotal(vec) :
# Calculating vector sum using
# accumulate function
Sum = sum(vec)
N = len(vec);
# Answer variable stores count
# of subsequences with desired sum
answer = 0;
# Bitmasking technique to generate
# all possible subsequences
for mask in range((1 << N)) :
# Variable curr counts the
# sum of the current subsequence
curr = 0;
for i in range(N) :
if ((mask & (1 << i)) != 0) :
# Include ith element
# of the vector
curr += vec[i];
if (curr == Sum - 2) :
answer += 1;
# Print the answer
print(answer);
# Driver Code
if __name__ == "__main__" :
# Initializing a vector
vec = [ 2, 0, 1, 2, 1 ];
countTotal(vec);
# This code is contributed by AnkThon
C#
// C# program for the above approach
using System;
public class GFG {
static int accumulate(int[] vec)
{
int sum1 = 0;
for (int i = 0; i < vec.Length; i++)
sum1 += vec[i];
return sum1;
}
// Function to count the total number
// of subsequences with sum S-2
static void countTotal(int[] vec)
{
// Calculating vector sum using
// accumulate function
int sum = accumulate(vec);
int N = vec.Length;
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
// Bitmasking technique to generate
// all possible subsequences
for (int mask = 0; mask < (1 << N); mask++) {
// Variable curr counts the
// sum of the current subsequence
int curr = 0;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) != 0) {
// Include ith element
// of the vector
curr += vec[i];
}
}
if (curr == sum - 2)
answer++;
}
// Print the answer
Console.WriteLine(answer);
}
// Driver Code
public static void Main(string[] args)
{
// Initializing a vector
int[] vec = { 2, 0, 1, 2, 1 };
countTotal(vec);
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// Javascript program for the above approach
// Function to count the total number
// of subsequences with sum S-2
function countTotal(vec) {
// Calculating vector sum using
// accumulate function
let sum = vec.reduce((acc, curr) => acc + curr, 0)
let N = vec.length;
// Answer variable stores count
// of subsequences with desired sum
let answer = 0;
// Bitmasking technique to generate
// all possible subsequences
for (let mask = 0; mask < (1 << N); mask++) {
// Variable curr counts the
// sum of the current subsequence
let curr = 0;
for (let i = 0; i < N; i++) {
if ((mask & (1 << i)) != 0) {
// Include ith element
// of the vector
curr += vec[i];
}
}
if (curr == sum - 2)
answer++;
}
// Print the answer
document.write(answer);
}
// Driver Code
// Initializing a vector
let vec = [2, 0, 1, 2, 1];
countTotal(vec);
// This code is contributed by saurabh_jaiswal.
</script>
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: The idea is to use the Combinatorics that apart from 0's, 1's, and 2's, all the other elements in our array will be part of the desired subsequences. Let's call them extra elements. Then, count the occurrences of 0's, 1's, and 2's in the array. Let's say the count of 0's is x, count of 1's be y, count of 2's be z.
- Let's count the number of desired subsequences if all 2's and extra elements are in the subsequence. Now there can be exactly y - 2 elements out of y. Note that there is no restriction for taking 0's as it contributes nothing to our subsequence sum.
- Hence, the total count of such subsequences = count1 = 2x × yCy - 2 = 2x × yC2 ( Since, nC0 + nC1 + . . . + nCn = 2n).
- Let's count the number of subsequences if all the 1's are in our subsequence. Now there can be exactly z - 1 elements out of z.
- Hence, the total count of such subsequences = count2 = 2x × zCz - 1 = 2x × zC1
- Total count of subsequences whose sum is equal to S - 2, count = count1 + count2 = 2x × ( yC2 + zC1 )
Follow the steps below to solve the problem:
- Initialize the variable sum as the sum of the array.
- Initialize the variable answer as 0 to store the answer.
- Initialize the variables countOfZero, countOfOne and countOfTwo to store the count of 0, 1 and 2.
- Traverse the array vec[] using the iterator x and perform the following tasks:
- Count the occurrences of 0's, 1's, and 2's.
- Initialize the variables value1 as 2countOfZero.
- Initialize the variable value2 as (countOfOne * (countOfOne - 1)) / 2.
- Initialize the variable value3 as countOfTwo.
- Set the value of answer as value1 * ( value2 + value).
- After performing the above steps, print the value of answer as the answer.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the total number
// of subsequences with sum S-2
void countTotal(vector<int>& vec)
{
// Calculating vector sum using
// accumulate function
int sum = accumulate(vec.begin(),
vec.end(), 0LL);
int N = (int)vec.size();
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
int countOfZero = 0,
countOfOne = 0,
countOfTwo = 0;
for (auto x : vec) {
if (x == 0)
countOfZero++;
else if (x == 1)
countOfOne++;
else if (x == 2)
countOfTwo++;
}
// Select any number of
// zeroes from 0 to count[0]
// which is equivalent
// to 2 ^ countOfZero
int value1 = pow(2, countOfZero);
// Considering all 2's
// and extra elements
int value2
= (countOfOne
* (countOfOne - 1))
/ 2;
// Considering all 1's
// and extra elements
int value3 = countOfTwo;
// Calculating final answer
answer = value1 * (value2 + value3);
// Print the answer
cout << answer;
}
// Driver Code
int main()
{
// Initializing a vector
vector<int> vec = { 2, 0, 1, 2, 1 };
countTotal(vec);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to count the total number
// of subsequences with sum S-2
static void countTotal(int[] arr)
{
int N = arr.length;
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
for (int i = 0; i < N; i++) {
if (arr[i] == 0)
countOfZero++;
else if (arr[i] == 1)
countOfOne++;
else if (arr[i] == 2)
countOfTwo++;
}
// Select any number of
// zeroes from 0 to count[0]
// which is equivalent
// to 2 ^ countOfZero
int value1 = (1 << countOfZero);
// Considering all 2's
// and extra elements
int value2 = (countOfOne * (countOfOne - 1)) / 2;
// Considering all 1's
// and extra elements
int value3 = countOfTwo;
// Calculating final answer
answer = value1 * (value2 + value3);
// Print the answer
System.out.println(answer);
}
// Driver Code
public static void main(String[] args)
{
// Initializing an array
int[] arr = { 2, 0, 1, 2, 1 };
countTotal(arr);
}
}
// This code is contributed by maddler.
Python3
# Python3 program for the above approach
# Function to count the total number
# of subsequences with sum S-2
def countTotal(vec) :
# Calculating vector sum using
# accumulate function
sum1 = sum(vec);
N = len(vec);
# Answer variable stores count
# of subsequences with desired sum
answer = 0;
countOfZero = 0; countOfOne = 0; countOfTwo = 0;
for x in vec :
if (x == 0) :
countOfZero += 1;
elif (x == 1) :
countOfOne += 1;
elif (x == 2) :
countOfTwo += 1;
# Select any number of
# zeroes from 0 to count[0]
# which is equivalent
# to 2 ^ countOfZero
value1 = 2 ** countOfZero;
# Considering all 2's
# and extra elements
value2 = (countOfOne * (countOfOne - 1)) // 2;
# Considering all 1's
# and extra elements
value3 = countOfTwo;
# Calculating final answer
answer = value1 * (value2 + value3);
# Print the answer
print(answer);
# Driver Code
if __name__ == "__main__" :
# Initializing a vector
vec = [ 2, 0, 1, 2, 1 ];
countTotal(vec);
# This code is contributed by AnkThon
C#
// Above approach implemented in C#
using System;
public class GFG {
// Function to count the total number
// of subsequences with sum S-2
static void countTotal(int[] arr)
{
int N = arr.Length;
// Answer variable stores count
// of subsequences with desired sum
int answer = 0;
int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
for (int i = 0; i < N; i++) {
if (arr[i] == 0)
countOfZero++;
else if (arr[i] == 1)
countOfOne++;
else if (arr[i] == 2)
countOfTwo++;
}
// Select any number of
// zeroes from 0 to count[0]
// which is equivalent
// to 2 ^ countOfZero
int value1 = (1 << countOfZero);
// Considering all 2's
// and extra elements
int value2 = (countOfOne * (countOfOne - 1)) / 2;
// Considering all 1's
// and extra elements
int value3 = countOfTwo;
// Calculating final answer
answer = value1 * (value2 + value3);
// Print the answer
Console.WriteLine(answer);
}
// Driver Code
public static void Main(string[] args)
{
// Initializing an array
int[] arr = { 2, 0, 1, 2, 1 };
countTotal(arr);
}
}
// This code is contributed by AnkThon
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to count the total number
// of subsequences with sum S-2
function countTotal(vec)
{
// Calculating vector sum using
// accumulate function
let sum = vec.reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
let N = vec.length;
// Answer variable stores count
// of subsequences with desired sum
let answer = 0;
let countOfZero = 0,
countOfOne = 0,
countOfTwo = 0;
for (let x of vec) {
if (x == 0)
countOfZero++;
else if (x == 1)
countOfOne++;
else if (x == 2)
countOfTwo++;
}
// Select any number of
// zeroes from 0 to count[0]
// which is equivalent
// to 2 ^ countOfZero
let value1 = Math.pow(2, countOfZero);
// Considering all 2's
// and extra elements
let value2
= (countOfOne
* (countOfOne - 1))
/ 2;
// Considering all 1's
// and extra elements
let value3 = countOfTwo;
// Calculating final answer
answer = value1 * (value2 + value3);
// Print the answer
document.write(answer);
}
// Driver Code
// Initializing a vector
let vec = [2, 0, 1, 2, 1];
countTotal(vec);
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Count of subsets with sum one less than the sum of Array
Given an array arr[ ] of size N. The task is to find the no of subsets with sum as (sum of the array - 1) when 0 occurs in an array or return -1 if there is no subset possible. Examples: Input: arr[ ] : {3, 0, 5, 2, 4} Output: -1Explanation: sum of array arr[ ] is 14 and there is not any subset with
12 min read
Count of subsequences in an array with sum less than or equal to X
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
13 min read
Count of subsets with sum equal to target
Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. Examples: Input: arr[] = [1, 2, 3, 3], target = 6 Output: 3 Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] Input: arr[] = [1, 1, 1, 1], target = 1
15+ min read
Count Subsequences with ordered integers in Array
Given an array nums[] of N positive integers, the task is to find the number of subsequences that can be created from the array where each subsequence contains all integers from 1 to its size in any order. If two subsequences have different chosen indices, then they are considered different. Example
7 min read
Find all subsequences with sum equals to K
Given an array arr[] of length n and a number k, the task is to find all the subsequences of the array with sum of its elements equal to k. Note: A subsequence is a subset that can be derived from an array by removing zero or more elements, without changing the order of the remaining elements. Examp
7 min read
Count sub-arrays which have elements less than or equal to X
Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4,
15 min read
Maximum subsequence sum such that no three are consecutive
Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present.Examples : Input: arr[] = {1, 2, 3}Output: 5We can't take three of them, so answer is2 + 3 = 5Input: arr[] = {3000, 2000, 1000, 3, 10}Output: 5013 3000 + 2000 + 3 + 10 = 5013
14 min read
Count of subarrays with unique sum with sum at most K
Given an array arr[] of size N and an integer K., The task is to count the number of subarrays with unique sum with sum at most K. Examples: Input: N = 3, arr[] = {1, 0, 1}, K = 1Output: 2Explanation: All Subarrays are [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] & The sum of these subarrays are {1,
4 min read
Count the Arithmetic sequences in the Array of size at least 3
Given an array arr[] of size N, the task is to find the count of all arithmetic sequences in the array. Examples: Input: arr = [1, 2, 3, 4] Output: 3 Explanation: The arithmetic sequences in arr are [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. Input: arr = [1, 3, 5, 6, 7, 8] Output: 4 Explanation:
6 min read
Count subsequences for every array element in which they are the maximum
Given an array arr[] consisting of N unique elements, the task is to generate an array B[] of length N such that B[i] is the number of subsequences in which arr[i] is the maximum element. Examples: Input: arr[] = {2, 3, 1}Output: {2, 4, 1}Explanation: Subsequences in which arr[0] ( = 2) is maximum a
11 min read