'Getting wrong answer while trying to solve Best sum problem using Dynamic programming
Trying to solve the best sum problem but I'm not getting the right answer using DP but if I remove the memoization part of this code then I'm getting the right answer.
I'm attaching the output screenshots:
PS: Please do not judge my code I'm trying to learn DP and I know that this code is not the best.
public class BestSum {
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5 };
int num = 10;
Map<Integer, List<Integer>> map = new HashMap<>();
List<Integer> list = rec(arr, num, map);
System.out.println(list);
}
static List<Integer> rec(int[] arr, int n, Map<Integer, List<Integer>> map) {
if (n == 0) {
return new ArrayList<>();
}
if (n < 0) {
return null;
}
if (map.containsKey(n)) {
return map.get(n);
}
List<Integer> sCombo = null;
for (int i : arr) {
int rem = n - i;
List<Integer> t = rec(arr, rem, map);
if (t != null) {
List<Integer> list = new ArrayList<>();
t.add(i);
list.addAll(t);
if (sCombo == null || list.size() < sCombo.size()) {
sCombo = list;
}
}
}
map.put(n, sCombo);
return map.get(n);
}
}
Solution 1:[1]
list.add(i); // write this instead of t.add(i).
a little mistake in the code nothing else.
Solution 2:[2]
just small mistake i.e.... you directly inserting sCombo into the Map. the values in sCombo array was changing while recursion every time at the same time the same sCombo array values in the map also changing because there have only one block of memory for each sCombo array that means when ever we edit that sCombo array it will effects the previous result....
example:- you assigned the list to sCombo sCombo=list;
when ever the list gets changes then the sCombo also changed
just clone() the object you get correct result like this......
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ujjwal Sahore |
| Solution 2 | Srinivas Peram |

