703041. Toppers Of Class
Toppers Of Class
Summary
Given a list of students and their marks in multiple subjects, find the topper for each subject. The topper is the student with the highest mark in that subject.
The problem involves sorting an array of arrays (student marks) based on individual subject scores, which requires knowledge of arrays and sorting algorithms.
Detailed Explanation
To solve this problem, we can iterate through each subject and find the maximum score for that subject. We then return the student with the maximum score as the topper for that subject.
Here's a step-by-step breakdown of the solution:
- Initialize an empty list to store the toppers for each subject.
- Iterate through each subject (considering multiple subjects).
- For each subject, find the maximum mark among all students.
- Find the student with the maximum mark in that subject.
- Add the student and their corresponding score to the list of toppers.
- Return the list of toppers.
The time complexity for this solution is O(n*m), where n is the number of subjects and m is the number of students. The space complexity is O(m), as we are storing the names of all students in memory.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<String> toppers(int[][] marks) {
List<String> toppers = new ArrayList<>();
for (int[] mark : marks) {
int maxMark = 0;
String topStudent = "";
for (int m : mark) {
if (m > maxMark) {
maxMark = m;
topStudent = "Student" + (mark.indexOf(m) + 1);
}
}
toppers.add(topStudent + ": " + maxMark);
}
return toppers;
}
public static void main(String[] args) {
int[][] marks = {{90, 80}, {70, 60}, {100, 90}};
List<String> result = toppers(marks);
for (String s : result) {
System.out.println(s);
}
}
}