The Form Largest Integer With Digits That Add up to Target interview question gives you an array cost of length 9, where cost[i] represents the cost of adding the digit i+1 (from 1 to 9) to your number. You have an exact target cost you must spend. You need to form the largest possible integer. The result is returned as a string since the number can be very large.
Google uses this Hard difficulty Dynamic Programming problem to test a candidate's ability to optimize for multiple criteria. To make an integer "large," you first want to maximize its length (number of digits), and then you want to maximize the values of the digits starting from the most significant bit. It evaluates if you can adapt the classic "Unbounded Knapsack" or "Coin Change" pattern to string generation.
This problem uses 1D Dynamic Programming.
dp[i] stores the maximum length of an integer that can be formed with exactly cost i. Initialize with (unreachable) and dp[0] = 0.target, try adding each digit d (1-9). dp[i] = max(dp[i], dp[i - cost[d-1]] + 1).target, work backward to build the string. At cost c, look for the largest digit d (from 9 down to 1) such that dp[c - cost[d-1]] == dp[c] - 1. Append d and update c.cost = [4,3,2,5,6,7,2,5,5], target = 9
dp[9 - 2] == dp[9] - 1 (i.e., dp[7] == 3). Yes, it is. Append "7", new target = 7.dp[i]. This causes massive memory overhead and string comparison slows down the DP transitions.In "Knapsack" problems where the output is a path or a sequence (like a string of digits), it is almost always better to let the DP compute only the "score" (length) and then do a second pass to trace back the optimal choices.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Coin Path | Hard | Solve | |
| Maximum Score from Performing Multiplication Operations | Hard | Solve | |
| Maximum XOR Score Subarray Queries | Hard | Solve | |
| Minimum Skips to Arrive at Meeting On Time | Hard | Solve | |
| Minimum Time to Finish the Race | Hard | Solve |