Skip to content

Commit 2f9739a

Browse files
authored
Update form-largest-integer-with-digits-that-add-up-to-target.cpp
1 parent b1393b9 commit 2f9739a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++/form-largest-integer-with-digits-that-add-up-to-target.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,36 @@ class Solution {
2828
return result;
2929
}
3030
};
31+
32+
// Time: O(t)
33+
// Space: O(t)
34+
class Solution2 {
35+
public:
36+
string largestNumber(vector<int>& cost, int target) {
37+
const auto& key = [](const auto& a) {
38+
return pair{accumulate(cbegin(a), cend(a), 0), a};
39+
};
40+
vector<vector<int>> dp = {vector<int>(9)};
41+
for (int t = 1; t <= target; ++t) {
42+
dp.emplace_back();
43+
for (int i = 0; i < 9; ++i) {
44+
if (t < cost[i] || dp[t - cost[i]].empty()) {
45+
continue;
46+
}
47+
auto curr = dp[t - cost[i]];
48+
++curr[8 - i];
49+
if (key(curr) > key(dp[t])) {
50+
dp[t] = move(curr);
51+
}
52+
}
53+
}
54+
if (dp.back().empty()) {
55+
return "0";
56+
}
57+
string result;
58+
for (int i = 0; i < dp.back().size(); ++i) {
59+
result += string(dp.back()[i], '1' + 8 - i);
60+
}
61+
return result;
62+
}
63+
};

0 commit comments

Comments
 (0)