1
// Space Complexity = O(N*M) (N == length of cost array and M == target )2
// Time Complexity = O(N*M)5
Map<String, String> map = new HashMap<>();8
public String largestNumber(int[] cost, int target) {9
memo = new String[cost.length + 1][target + 1];11
for (int i = 0; i <= cost.length; i++) {12
for (int j = 0; j <= target; j++) memo[i][j] = "0";15
String res = helper(cost, cost.length - 1, target);17
return res == "-1" ? "0" : res;20
public String helper(int[] cost, int index, int target) {25
if (target < 0) return "-1";27
if (index < 0) return "-1";29
if (memo[index][target] != "0") return memo[index][target];31
String str1 = (index + 1) + helper(cost, cost.length - 1, target - cost[index]);32
String str2 = helper(cost, index - 1, target);34
String res = getBigger(str1, str2);36
memo[index][target] = res;41
public String getBigger(String num1, String num2) {42
if (num1.contains("-1")) return num2;43
if (num2.contains("-1")) return num1;44
if (num1.length() > num2.length()) return num1;45
if (num2.length() > num1.length()) return num2;46
return Double.parseDouble(num1) < Double.parseDouble(num2) ? num2 : num1;