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
Understanding the Visualization
1
Input
Array of decimal prices and integer target sum
2
Process
Round each price up or down to minimize total error
3
Output
Minimum total rounding error as string with 3 decimal places
Key Takeaway
🎯 Key Insight: Round numbers with smaller fractional parts up first to minimize total rounding error
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code