Approach
Sorting and greedy selection
For Maximize Profit from Task Assignment, 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
- 30 lines of Java from the credited upstream file 3476.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 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 long maxProfit(int[] workers, int[][] tasks) {3 long totalProfit = 0;4 int maxRemainingProfit = 0;5 Map<Integer, List<Integer>> skillToProfits = new HashMap<>();6 7 for (int[] task : tasks) {8 final int skill = task[0];9 final int profit = task[1];10 skillToProfits.computeIfAbsent(skill, k -> new ArrayList<>()).add(profit);11 }12 13 for (List<Integer> profits : skillToProfits.values())14 Collections.sort(profits, Collections.reverseOrder());15 16 for (final int workerSkill : workers)17 if (skillToProfits.containsKey(workerSkill) && !skillToProfits.get(workerSkill).isEmpty()) {18 final int profit = skillToProfits.get(workerSkill).get(0);19 skillToProfits.get(workerSkill).remove(0);20 totalProfit += profit;21 }22 23 for (List<Integer> profits : skillToProfits.values())24 if (!profits.isEmpty())25 maxRemainingProfit = Math.max(maxRemainingProfit, profits.get(0));26 27 return totalProfit + maxRemainingProfit;28 }29}30