Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmSum of all maximum frequency elements in Matrix

Sum of all maximum frequency elements in Matrix

Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all maximum occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix.

Examples

Input : mat[] = {{1, 1, 1},
                {2, 3, 3},
                {4, 5, 3}}
Output : 12
The max occurring elements are 3 and 1
Therefore, sum = 1 + 1 + 1 + 3 + 3 + 3 = 12

Input : mat[] = {{10, 20},
                 {40, 40}}
Output : 80

Approach

  • Traverse the matrix and use a hash table to store the frequencies of elements of the matrix such that the key of map is the matrix element and value is its frequency in the matrix.
  • Then traverse the map to find the maximum frequency.
  • Finally, traverse the hash table to find the frequency of elements and check if it matches with the maximum frequency obtained in previous step, if yes, then add this element it’s frequency times to sum.

Below is the implementation of the above approach: 

C++




// C++ program to find sum of all max
// frequency elements in a Matrix
 
#include <bits/stdc++.h>
using namespace std;
 
#define N 3 // Rows
#define M 3 // Columns
 
// Function to find sum of all max
// frequency elements in a Matrix
int sumMaxOccurring(int arr[N][M])
{
    // Store frequencies of elements
    // in matrix
    unordered_map<int, int> mp;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            mp[arr[i][j]]++;
        }
    }
 
    // loop to iterate through map
    // and find the maximum frequency
    int sum = 0;
    int maxFreq = INT_MIN;
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {
        if (itr->second > maxFreq)
            maxFreq = itr->second;
    }
 
    // Sum of maximum frequency elements
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {       
        if (itr->second == maxFreq) {
            sum += (itr->first) * (itr->second);
        }
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int mat[N][M] = { { 1, 2, 3 },
                      { 1, 3, 2 },
                      { 1, 5, 6 } };
 
    cout << sumMaxOccurring(mat) << endl;
 
    return 0;
}


Java




// Java program to find sum of all max
// frequency elements in a Matrix
import java.util.*;
 
class GFG
{
 
    static int N = 3; // Rows
    static int M = 3; // Columns
 
    // Function to find sum of all max
    // frequency elements in a Matrix
    static int sumMaxOccurring(int arr[][])
    {
        // Store frequencies of elements
        // in matrix
        Map<Integer, Integer> mp = new HashMap<>();
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if (mp.containsKey(arr[i][j]))
                {
                    mp.put(arr[i][j], mp.get(arr[i][j]) + 1);
                }
                else
                {
                    mp.put(arr[i][j], 1);
                }
            }
        }
 
        // loop to iterate through map
        // and find the maximum frequency
        int sum = 0;
        int maxFreq = Integer.MIN_VALUE;
        for (Map.Entry<Integer, Integer> itr : mp.entrySet())
        {
            if (itr.getValue() > maxFreq)
            {
                maxFreq = itr.getValue();
            }
        }
 
        // Sum of maximum frequency elements
        for (Map.Entry<Integer, Integer> itr : mp.entrySet())
        {
            if (itr.getValue() == maxFreq)
            {
                sum += (itr.getKey()) * (itr.getValue());
            }
        }
 
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int mat[][] = {{1, 2, 3},
                        {1, 3, 2},
                        {1, 5, 6}};
 
        System.out.println(sumMaxOccurring(mat));
    }
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to find sum of all max
# frequency elements in a Matrix
import sys
 
N = 3 # Rows
M = 3 # Columns
 
# Function to find sum of all max
# frequency elements in a Matrix
def sumMaxOccurring(arr):
 
    # Store frequencies of elements
    # in matrix
    mp = dict()
    for i in range(N):
        for j in range(M):
            if arr[i][j] in mp:
                mp[arr[i][j]] += 1
            else:
                mp[arr[i][j]] = 1
 
    # loop to iterate through map
    # and find the maximum frequency
    s = 0
    maxFreq = -sys.maxsize
    for i in mp:
        if mp[i] > maxFreq:
            maxFreq = mp[i]
 
    # Sum of maximum frequency elements
    for i in mp:
        if mp[i] == maxFreq:
            s += i * mp[i]
 
    return s
 
# Driver code
if __name__ == "__main__":
    mat = [[1, 2, 3],
           [1, 3, 2],
           [1, 5, 6]]
 
    print(sumMaxOccurring(mat))
 
# This code is contributed by
# sanjeev2552


C#




// C# program to find sum of all max
// frequency elements in a Matrix
using System;
using System.Collections.Generic;   
public class GFG
{
  
    static int N = 3; // Rows
    static int M = 3; // Columns
  
    // Function to find sum of all max
    // frequency elements in a Matrix
    static int sumMaxOccurring(int [,]arr)
    {
        // Store frequencies of elements
        // in matrix
        Dictionary<int,int> mp = new Dictionary<int,int>();
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if (mp.ContainsKey(arr[i,j]))
                {
                    var v= mp[arr[i,j]];
                    mp.Remove(arr[i,j]);
                    mp.Add(arr[i,j], v + 1);
                }
                else
                {
                    mp.Add(arr[i,j], 1);
                }
            }
        }
  
        // loop to iterate through map
        // and find the maximum frequency
        int sum = 0;
        int maxFreq = int.MinValue;
        foreach(KeyValuePair<int, int> itr in mp)
        {
            if (itr.Value > maxFreq)
            {
                maxFreq = itr.Value;
            }
        }
  
        // Sum of maximum frequency elements
        foreach(KeyValuePair<int, int> itr in mp)
        {
            if (itr.Value == maxFreq)
            {
                sum += (itr.Key) * (itr.Value);
            }
        }
  
        return sum;
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        int [,]mat = {{1, 2, 3},
                        {1, 3, 2},
                        {1, 5, 6}};
  
        Console.WriteLine(sumMaxOccurring(mat));
    }
}
// This code contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript program to find sum of all max
// frequency elements in a Matrix
 
var N = 3; // Rows
var M = 3; // Columns
 
// Function to find sum of all max
// frequency elements in a Matrix
function sumMaxOccurring(arr)
{
    // Store frequencies of elements
    // in matrix
    var mp = new Map();
    for (var i = 0; i < N; i++)
    {
        for (var j = 0; j < M; j++)
        {
            if (mp.has(arr[i][j]))
            {
                var v= mp.get(arr[i][j]);
                mp.delete(arr[i][j]);
                mp.set(arr[i][j], v + 1);
            }
            else
            {
                mp.set(arr[i][j], 1);
            }
        }
    }
 
    // loop to iterate through map
    // and find the maximum frequency
    var sum = 0;
    var maxFreq = -1000000000;
 
    mp.forEach((value, key) => {
        if (value > maxFreq)
        {
            maxFreq = value;
        }
    });
 
    // Sum of maximum frequency elements
    mp.forEach((value, key) => {
         
        if (value == maxFreq)
        {
            sum += (key) * (value);
        }
    });
 
    return sum;
}
 
// Driver Code
var mat = [[1, 2, 3],
                [1, 3, 2],
                [1, 5, 6]];
document.write(sumMaxOccurring(mat));
 
 
</script>


Output

3

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments