LeetCode 1449: Form Largest Integer With Digits That Add up to Target Solution
Master LeetCode problem 1449 (Form Largest Integer With Digits That Add up to Target), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1449. Form Largest Integer With Digits That Add up to Target
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We create a 1D array dp where dp[i] represents the maximum number we can form with a cost equal to i. We iterate over each digit cost and update the dp array accordingly. Finally, we build the result string by backtracking through the dp array.
- Initialize
dparray with sizetarget + 1and fill it with-1(to indicate it's not possible to form a number with that cost). - Set
dp[0] = 0as the cost of forming number '0' is 0. - Iterate over each digit cost and update
dparray. - Backtrack through the
dparray to build the result string.
Time Complexity: O(target) where target is the given target value. Space Complexity: O(target) for the dp array.
:
Solution Code
class Solution {
public String largestNumber(int[] cost, int target) {
int[] dp = new int[target + 1];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < 9; j++) {
if (i - cost[j] >= 0 && dp[i - cost[j]] >= 0) {
dp[i] = Math.max(dp[i], dp[i - cost[j]] + 1);
}
}
}
if (dp[target] < 0) {
return "0";
}
StringBuilder sb = new StringBuilder();
for (int i = 8; i >= 0; i--) {
while (target - cost[i] >= 0 && dp[target] == dp[target - cost[i]] + 1) {
sb.append(i + 1);
target -= cost[i];
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1449 (Form Largest Integer With Digits That Add up to Target)?
This page provides optimized solutions for LeetCode problem 1449 (Form Largest Integer With Digits That Add up to Target) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1449 (Form Largest Integer With Digits That Add up to Target)?
The time complexity for LeetCode 1449 (Form Largest Integer With Digits That Add up to Target) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1449 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1449 in Java, C++, or Python.