Skip to content

Commit 02e36d6

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

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(t)
2+
# Space: O(t)
3+
4+
class Solution(object):
5+
def largestNumber(self, cost, target):
6+
"""
7+
:type cost: List[int]
8+
:type target: int
9+
:rtype: str
10+
"""
11+
dp = [0] + [-1]*(target)
12+
for t in xrange(1, target+1):
13+
for i, c in enumerate(cost):
14+
if t-c < 0 or dp[t-c] < 0:
15+
continue
16+
dp[t] = max(dp[t], dp[t-c]+1)
17+
if dp[target] < 0:
18+
return "0"
19+
result = []
20+
for i in reversed(xrange(1, 9)):
21+
while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:
22+
target -= cost[i]
23+
result.append(i)
24+
return "".join(map(str, result))
25+
26+
27+
# Time: O(t^2)
28+
# Space: O(t^2)
29+
class Solution(object):
30+
def largestNumber(self, cost, target):
31+
"""
32+
:type cost: List[int]
33+
:type target: int
34+
:rtype: str
35+
"""
36+
dp = [0] + [-1]*(target)
37+
for t in xrange(1, target+1):
38+
for i, c in enumerate(cost):
39+
if t-c < 0:
40+
continue
41+
dp[t] = max(dp[t], dp[t-c]*10 + i+1)
42+
return str(max(dp[t], 0))

0 commit comments

Comments
 (0)