[LeetCode] Form Largest Integer With Digits That Add up to Target

1449. Form Largest Integer With Digits That Add up to Target

Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:

  • The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
  • The total cost used must be equal to target.
  • The integer does not have 0 digits.

Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return “0”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
string large(string a, string b) {
if(a.length() != b.length()) return a.length() > b.length() ? a : b;
vector<int> freq(10);
for(int i = 0; i < a.length(); i++) freq[a[i]-'0']++;
for(int i = 0; i < b.length(); i++) freq[b[i]-'0']--;
for(int i = 9; i > 0; i--) {
if(freq[i] == 0) continue;
return freq[i] > 0 ? a : b;
}
return a;
}
public:
string largestNumber(vector<int>& cost, int target) {
unordered_map<int, int> mp;
for(int i = 0; i < cost.size(); i++) {
mp[cost[i]] = i + 1;
}
vector<string> dp(target + 1, "");
for(int i = 1; i <= target; i++) {
for(auto& [cost, num] : mp) {
if(cost == i) {
dp[i] = large(dp[i], string(1, num + '0'));
} else if(i > cost and dp[i-cost] != "") {
string now = dp[i-cost];
now.push_back(num + '0');
dp[i] = large(dp[i], now);
}
}
}
sort(rbegin(dp[target]), rend(dp[target]));
return dp[target] == "" ? "0" : dp[target];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/26/PS/LeetCode/form-largest-integer-with-digits-that-add-up-to-target/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.