Minimize Rounding Error to Meet Target
Given an array of prices[p1,p2...,pn]
and atarget
, round each pricepi
toRoundi(pi)
so that the rounded array[Round1(p1),Round2(p2)...,Roundn(pn)]
sums to the giventarget
. Each operationRoundi(pi)
could be eitherFloor(pi)
orCeil(pi)
.
Return the string"-1"
if the rounded array is impossible to sum totarget
. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| forifrom 1 ton, as a string with three places after the decimal.
Example 1:
Example 2:
Note:
1
<
= prices.length
<
= 500
.
Each string of prices
prices[i]
represents a real number which is between 0 and 1000 and has exactly 3 decimal places.
target
is between 0 and 1000000.
分析
int和floor差不多,也是切头,3 = 3.000 True
这里算出max和min,中间差的就是floor或者ceil。 max-target就是多出来的,需要floor的数字。
记住map和filter都要变List
format用法:"{:.3f}".format(res)
Last updated
Was this helpful?