Monday 23 January 2017

Winner

Athlos has a total of N events. Each event has M matches. The winner of each of these NxM matches is given to you in the form of a grid. 

The grid contains N horizontal lines denoting each event and M vertical lines denoting the M matches of each event. There are a total of NxM students each having a unique id between 1 to NxM. The jth element of the ith line denotes the id of the winner of that match. 

Given the grid you need to help Ruben determine the ultimate winner i.e. the student who has won maximum number of matches. In case there are more than one student with same number of matches won then print the least id amongst all.
Input Format
Input consists of T testcases. First line of each case consists of two space seperated integers N, M denoting the number of events and number of matches in each event. That is followed by N lines each containing M integers denoting the winners of each match.
Constraints
1 ≤ T ≤ 10
1 ≤ N, M ≤ 600
1 ≤ Winner's id (aij) ≤ N*M
Output Format
For each testcase print one line containing the id of the ultimate winner i.e. the student who won the maximum number of matches. (In case of tie print the id which is least).
Sample Input 0
2
2 2
1 2
3 3
2 2
1 1
4 4
Sample Output 0
3
1
source code:
import java.io.*;
import java.util.*;
import java.util.Collections;
public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
            {
            int n=sc.nextInt();
            int m=sc.nextInt();
             int q[]=new int[n*m+1];
            q[0]=0;int max=0;
             for(int j=1;j<=n*m;j++)
             {
                 int temp=sc.nextInt();///storing frequency of winning of a player
               q[temp]++;
                 
                if(q[temp]>q[max])//comparing the greatest winner
                   { 
                      max=temp;
                   }
                if(q[temp]==q[max] && temp<max)//if two people with same no.of //wins then placing the winner with least id
                    max=temp;
            }
            System.out.println(max);
            
        }
        
    }
}

No comments:

Post a Comment