Approach
Sorting and greedy selection
For Rearranging Fruits, 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
- 31 lines of Java from the credited upstream file 2561.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 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 minCost(int[] basket1, int[] basket2) {3 long ans = 0;4 List<Integer> swapped = new ArrayList<>();5 Map<Integer, Integer> count = new HashMap<>();6 7 for (final int b : basket1)8 count.merge(b, 1, Integer::sum);9 10 for (final int b : basket2)11 count.merge(b, -1, Integer::sum);12 13 for (Map.Entry<Integer, Integer> entry : count.entrySet()) {14 final Integer num = entry.getKey();15 final Integer freq = entry.getValue();16 if (freq % 2 != 0)17 return -1;18 for (int i = 0; i < Math.abs(freq) / 2; ++i)19 swapped.add(num);20 }21 22 final int minNum =23 Math.min(Arrays.stream(basket1).min().getAsInt(), Arrays.stream(basket2).min().getAsInt());24 Collections.sort(swapped);25 26 for (int i = 0; i < swapped.size() / 2; ++i)27 ans += Math.min(minNum * 2, swapped.get(i));28 return ans;29 }30}31