LeetCode 1058, Medium. Topics: Array, Math, String, Dynamic Programming, Greedy, Sorting. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:
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.
Examples
Constraints
- 1 <= prices.length <= 500
- Each string prices[i] represents a real number in the range [0.0, 1000.0] and has exactly 3 decimal places.
- 0 <= target <= 10^6
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026