Number of subsets whose mean is maximum
Last Updated :
10 Mar, 2022
Given an array arr[] of size N, the task is to count the number of subsets of arr[] whose mean is maximum.
Examples:
Input: arr[] = {1, 2, 1, 2}
Output: 3
Subsets with maximum mean are {2}, {2} and {2, 2}.
Input: arr[] = {1}
Output: 1
Approach: The maximum value for the mean of any subset will be when the subset will only consist of the maximum element from the array. So, in order to count all the possible subsets, find the frequency of the maximum element from the array say cnt and the count of possible subsets will be 2cnt – 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntSubSets( int arr[], int n)
{
int maxVal = *max_element(arr, arr + n);
int cnt = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == maxVal)
cnt++;
}
return ( pow (2, cnt) - 1);
}
int main()
{
int arr[] = { 1, 2, 1, 2 };
int n = sizeof (arr) / sizeof ( int );
cout << cntSubSets(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int cntSubSets( int arr[], int n)
{
int maxVal = Arrays.stream(arr).max().getAsInt();
int cnt = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] == maxVal)
cnt++;
}
return ( int ) (Math.pow( 2 , cnt) - 1 );
}
public static void main(String []args)
{
int arr[] = { 1 , 2 , 1 , 2 };
int n = arr.length;
System.out.println(cntSubSets(arr, n));
}
}
|
Python3
def cntSubSets(arr, n) :
maxVal = max (arr);
cnt = 0 ;
for i in range (n) :
if (arr[i] = = maxVal) :
cnt + = 1 ;
return (( 2 * * cnt) - 1 );
if __name__ = = "__main__" :
arr = [ 1 , 2 , 1 , 2 ];
n = len (arr);
print (cntSubSets(arr, n));
|
C#
using System;
using System.Linq;
class GFG
{
static int cntSubSets( int []arr, int n)
{
int maxVal = arr.Max();
int cnt = 0;
for ( int i = 0; i < n; i++)
{
if (arr[i] == maxVal)
cnt++;
}
return ( int ) (Math.Pow(2, cnt) - 1);
}
public static void Main(String []args)
{
int []arr = { 1, 2, 1, 2 };
int n = arr.Length;
Console.WriteLine(cntSubSets(arr, n));
}
}
|
Javascript
<script>
function cntSubSets(arr, n)
{
var maxVal = arr.reduce( function (a, b)
{
return Math.max(a, b);
});
var cnt = 0;
for ( var i = 0; i < n; i++) {
if (arr[i] == maxVal)
cnt++;
}
return (Math.pow(2, cnt) - 1);
}
var arr = [ 1, 2, 1, 2 ]
var n = arr.length;
document.write(cntSubSets(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...