Minimize Rounding Error to Meet Target - Problem

Given an array of prices [p1, p2, ..., pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1), Round2(p2), ..., Roundn(pn)] sums to the given target.

Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi).

Return the string "-1" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - pi| for i from 1 to n, as a string with three places after the decimal.

Input & Output

Example 1 — Basic Case
$ Input: prices = [0.700,2.800,4.900], target = 8
Output: "1.000"
💡 Note: Round to [1,3,5] to get sum=9>8. Round to [1,3,4] to get sum=8 with error |1-0.7|+|3-2.8|+|4-4.9|=0.3+0.2+0.9=1.4. But round to [0,3,5] gets sum=8 with error 0.7+0.2+0.1=1.0 which is better.
Example 2 — Impossible Case
$ Input: prices = [1.000,4.000,7.000], target = 20
Output: "-1"
💡 Note: Maximum possible sum is 1+4+7=12, which is less than target 20, so it's impossible.
Example 3 — All Integers
$ Input: prices = [1.500,2.500,3.500], target = 6
Output: "1.500"
💡 Note: Round to [1,2,3] gives sum=6. Error is |1-1.5|+|2-2.5|+|3-3.5|=0.5+0.5+0.5=1.5.

Constraints

  • 1 ≤ prices.length ≤ 104
  • 0 ≤ prices[i] ≤ 104
  • 0 ≤ target ≤ 5 * 104

Visualization

Tap to expand
Minimize Rounding Error to Meet Target INPUT prices[] Array 0.700 p1 2.800 p2 4.900 p3 Target Sum 8 Fractional Parts: 0.7 0.8 0.9 Sum Range: Floor: 0+2+4 = 6 Ceil: 1+3+5 = 9 8 is in [6,9] - OK ALGORITHM STEPS 1 Calculate Bounds sumFloor=6, sumCeil=9 Need k=2 ceils (8-6) 2 Sort by Frac. Cost Ceil cost = 1-frac 0.3, 0.2, 0.1 (sorted) 3 Greedy Selection Pick 2 smallest ceil costs 4.9 ceil-->5 2.8 ceil-->3 0.7 floor-->0 4 Calculate Error |5-4.9| = 0.1 |3-2.8| = 0.2 |0-0.7| = 0.7 Total = 1.000 FINAL RESULT Rounded Values 0 floor(0.7) 3 ceil(2.8) 5 ceil(4.9) Sum: 0 + 3 + 5 = 8 Matches Target - OK Rounding Error |0 - 0.700| = 0.700 |3 - 2.800| = 0.200 |5 - 4.900| = 0.100 Total = 1.000 Output: "1.000" Key Insight: The greedy approach works because ceiling a value costs (1 - fractional part) in error, while flooring costs (fractional part). To minimize total error when we need k ceilings, we ceil the k values with LARGEST fractional parts (smallest ceil cost: 1-frac). TutorialsPoint - Minimize Rounding Error to Meet Target | Greedy by Fractional Part
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
385 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen