Approach
Sorting and greedy selection
For Reward Top K Students, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 29 lines of Java from the credited upstream file 2512.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback,3 String[] report, int[] student_id, int k) {4 List<Integer> ans = new ArrayList<>();5 Pair<Integer, Integer>[] scoreAndIds = new Pair[report.length];6 Set<String> pos = Arrays.stream(positive_feedback).collect(Collectors.toSet());7 Set<String> neg = Arrays.stream(negative_feedback).collect(Collectors.toSet());8 9 for (int i = 0; i < report.length; ++i) {10 int score = 0;11 for (final String word : report[i].split(" ")) {12 if (pos.contains(word))13 score += 3;14 if (neg.contains(word))15 score -= 1;16 }17 scoreAndIds[i] = new Pair<>(score, student_id[i]);18 }19 20 Arrays.sort(scoreAndIds,21 Comparator.comparing(Pair<Integer, Integer>::getKey, Comparator.reverseOrder())22 .thenComparing(Pair<Integer, Integer>::getValue));23 24 for (int i = 0; i < k; ++i)25 ans.add(scoreAndIds[i].getValue());26 return ans;27 }28}29