Approach
Sorting and greedy selection
For Minimize Rounding Error to Meet Target, 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
- 40 lines of Java from the credited upstream file 1058.java.
- The implementation visibly relies on sequence storage.
- 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 String minimizeError(String[] prices, int target) {3 4 5 List<double[]> A = new ArrayList<>();6 int sumFloored = 0;7 int sumCeiled = 0;8 9 for (final String p : prices) {10 final double price = Double.parseDouble(p);11 final int floored = (int) Math.floor(price);12 final int ceiled = (int) Math.ceil(price);13 sumFloored += floored;14 sumCeiled += ceiled;15 final double costFloor = price - (double) floored;16 final double costCeil = (double) ceiled - price;17 A.add(new double[] {costCeil - costFloor, costCeil, costFloor});18 }19 20 if (sumFloored > target || sumCeiled < target)21 return "-1";22 23 Collections.sort(A, new Comparator<double[]>() {24 @Override25 public int compare(double[] a, double[] b) {26 return Double.compare(a[0], b[0]);27 }28 });29 30 double sumError = 0.0;31 final int nCeiled = target - sumFloored;32 for (int i = 0; i < nCeiled; ++i)33 sumError += A.get(i)[1];34 for (int i = nCeiled; i < A.size(); ++i)35 sumError += A.get(i)[2];36 37 return String.format("%.3f", sumError);38 }39}40