I am new to dynamic programming and I am trying to understand the basics of recursion and memoization while trying to solve the Max sum of non adjacent elements - Problem. After reading some theory, one of the basic properties of a recursive function is it should have over lapping sub problems. For the naïve brute force approach to this problem, for my code below, I am having a hard time seeing overlapping problems.
- Is the reason I am not able to see overlapping sub problems because I don't have a recursive relation?
- Do I always have to have a recurrence relation in order to have sub problems, i.e., all recursive problems may/may not have sub problems if there is no recurrence relation
- How can I add memoization if 1 or 2 is holds and I just made a mistake in analysis?
public static int maxSubsetSum(int[] arr) {
HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
return maxSumHelper(arr, 0, arr.length , 0, new ArrayList<Integer>(), cache);
}
public static int maxSumHelper(int[]arr, int start, int end, int sum, ArrayList<Integer>combo, HashMap<Integer, Integer> cache){
/*
* if(cache.containsKey(start)) { return; }
*/
if(start>=end){
for(int i = 0; i <combo.size();i++ ) {
System.out.print(combo.get(i));
}
System.out.println();
return sum;
}
for(int i = start; i < arr.length; i++){
sum+= arr[i];
combo.add(arr[i]);
int withMax = maxSumHelper(arr, i + 2, end, sum, combo, cache);
sum-=arr[i];
combo.remove(combo.size() - 1);
int withoutMax = maxSumHelper(arr, i+ 2, end, sum, combo, cache);
//cache.put(i, Math.max(withMax, withoutMax));
max = Math.max(max,Math.max(withMax, withoutMax));
}
return max;
}
withoutMax = maxSumHelper(arr, i+ 2, end, sum, combo, cache)looks wrong to me. Shouldn't that be a+1?ithough.