Skip to content

Commit f4cbd56

Browse files
authored
Update form-largest-integer-with-digits-that-add-up-to-target.py
1 parent 02e36d6 commit f4cbd56

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

Python/form-largest-integer-with-digits-that-add-up-to-target.py

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,62 @@ def largestNumber(self, cost, target):
88
:type target: int
99
:rtype: str
1010
"""
11-
dp = [0] + [-1]*(target)
11+
dp = [0]
1212
for t in xrange(1, target+1):
13+
dp.append(-1)
1314
for i, c in enumerate(cost):
1415
if t-c < 0 or dp[t-c] < 0:
1516
continue
1617
dp[t] = max(dp[t], dp[t-c]+1)
1718
if dp[target] < 0:
1819
return "0"
1920
result = []
20-
for i in reversed(xrange(1, 9)):
21+
for i in reversed(xrange(9)):
2122
while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:
2223
target -= cost[i]
23-
result.append(i)
24+
result.append(i+1)
2425
return "".join(map(str, result))
2526

2627

28+
# Time: O(t)
29+
# Space: O(t)
30+
class Solution2(object):
31+
def largestNumber(self, cost, target):
32+
"""
33+
:type cost: List[int]
34+
:type target: int
35+
:rtype: str
36+
"""
37+
def key(bag):
38+
return sum(bag), bag
39+
40+
dp = [[0]*9]
41+
for t in xrange(1, target+1):
42+
dp.append([])
43+
for d, c in enumerate(cost):
44+
if t < c or not dp[t-c]:
45+
continue
46+
curr = dp[t-c][:]
47+
curr[~d] += 1
48+
if key(curr) > key(dp[t]):
49+
dp[-1] = curr
50+
if not dp[-1]:
51+
return "0"
52+
return "".join(str(9-i)*c for i, c in enumerate(dp[-1]))
53+
54+
2755
# Time: O(t^2)
2856
# Space: O(t^2)
29-
class Solution(object):
57+
class Solution3(object):
3058
def largestNumber(self, cost, target):
3159
"""
3260
:type cost: List[int]
3361
:type target: int
3462
:rtype: str
3563
"""
36-
dp = [0] + [-1]*(target)
64+
dp = [0]
3765
for t in xrange(1, target+1):
66+
dp.append(-1)
3867
for i, c in enumerate(cost):
3968
if t-c < 0:
4069
continue

0 commit comments

Comments
 (0)