Skip to content

Commit 478cd85

Browse files
committed
1058 Minimize Rounding Error to Meet Target
1 parent af0b62b commit 478cd85

File tree

2 files changed

+71
-3
lines changed

2 files changed

+71
-3
lines changed

1000 Minimum Cost to Merge Stones.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ def mergeStones(self, stones: List[int], K: int) -> int:
7272
7373
Answer:
7474
F[i][j][m] = cost of merge A[i:j] into m piles
75-
F[i][j][1] = F[i][j][k] + sum(stones[i:j])
76-
F[i][j][m] = min F[i][mid][1] + F[mid][j][m-1]
75+
F[i][j][1] = F[i][j][k] + sum(stones[i:j]) # merge
76+
F[i][j][m] = min F[i][mid][1] + F[mid][j][m-1] # add
7777
7878
initial:
7979
F[i][i+1][1] = 0
@@ -100,7 +100,7 @@ def F(i, j, m):
100100
if m == 1:
101101
return 0
102102
return float("inf")
103-
103+
104104
if m == 1:
105105
return F(i, j, K) + sums[j] - sums[i]
106106

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given an array of prices [p1,p2...,pn] and a target, round each price pi to
4+
Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums
5+
to the given target. Each operation Roundi(pi) could be either Floor(pi) or
6+
Ceil(pi).
7+
8+
Return the string "-1" if the rounded array is impossible to sum to target.
9+
Otherwise, return the smallest rounding error, which is defined as
10+
Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string with three places after the
11+
decimal.
12+
13+
14+
15+
Example 1:
16+
17+
Input: prices = ["0.700","2.800","4.900"], target = 8
18+
Output: "1.000"
19+
Explanation:
20+
Use Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) =
21+
0.7 + 0.2 + 0.1 = 1.0 .
22+
Example 2:
23+
24+
Input: prices = ["1.500","2.500","3.500"], target = 10
25+
Output: "-1"
26+
Explanation:
27+
It is impossible to meet the target.
28+
29+
30+
Note:
31+
32+
1 <= prices.length <= 500.
33+
Each string of prices prices[i] represents a real number which is between 0 and
34+
1000 and has exactly 3 decimal places.
35+
target is between 0 and 1000000.
36+
"""
37+
from typing import List
38+
import math
39+
40+
41+
class Solution:
42+
def minimizeError(self, prices: List[str], target: int) -> str:
43+
"""
44+
to determine possible, floor all or ceil all
45+
46+
floor all, sort by floor error inverse, make the adjustment
47+
"""
48+
A = list(map(float, prices))
49+
f_sum = sum(map(math.floor, A))
50+
c_sum = sum(map(math.ceil, A))
51+
if not f_sum <= target <= c_sum:
52+
return "-1"
53+
54+
errors = [
55+
e - math.floor(e)
56+
for e in A
57+
]
58+
errors.sort(reverse=True)
59+
ret = 0
60+
remain = target - f_sum
61+
for err in errors:
62+
if remain > 0:
63+
ret += 1 - err
64+
remain -= 1
65+
else:
66+
ret += err
67+
68+
return f'{ret:.{3}f}'

0 commit comments

Comments
 (0)