Ctrl K

Round Prices to a Total

Medium
You are given a list prices of strings, each with exactly three digits after the point, such as "4.800". Every price p must be rounded to an integer, either down to ⌊p⌋ or up to ⌈p⌉ (for a whole price both are the same). The rounded prices must add up to exactly total. The rounding error is the sum of |rounded − original| over all prices. Return the smallest possible error as a string with three digits after the point (for example "1.000"). If the sum total cannot be reached, return "-1".
Example 1
prices=['2.300', '4.800', '1.500'], total=9 → '1.000'

Rounding everything down gives 2 + 4 + 1 = 7, so exactly two prices must go up. The cheapest choice is 4.800 → 5 and 1.500 → 2, with 2.300 → 2: the error is 0.2 + 0.5 + 0.3 = 1.000.

Example 2
prices=['3.000', '0.250'], total=5 → '-1'

The largest reachable sum is 3 + 1 = 4, so the answer is "-1".

Example 3
prices=['0.999', '7.000'], total=8 → '0.001'
Constraints
  • 1 ≤ len(prices) ≤ 500
  • Each prices[i] is a number from 0 to 1000 with exactly three digits after the point
  • 0 ≤ total ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumClosest Clock Readings MediumUp or Down for Every Post MediumThe Middle Bag MediumPrices That Fade With Each Sale Medium
loading Python…
Input
prices=['2.300', '4.800', '1.500'], total=9
Expected
'1.000'

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.