I am struggling very badly for recursive + cache/memoize solution. I read some solutions online and the idea is to start with the last balloon and work up. Here is the code for the solution:
class Solution {
int [][] cache;
public int maxCoins(int[] nums) {
cache = new int[nums.length + 5][nums.length + 5];
for(int [] arr : cache)
Arrays.fill(arr, -1);
return helper(nums, 0, nums.length - 1);
}
public int helper(int [] nums, int left, int right){
if(right < left)
return 0;
if(cache[left][right] != -1)
return cache[left][right];
for(int i = left; i <= right; ++i){
cache[left][right] = Math.max(cache[left][right], nums[i]*getVal(nums, left - 1)*getVal(nums, right + 1) + helper(nums, left, i - 1) + helper(nums, i + 1, right)); /////HELP ME HERE!
}
return cache[left][right];
}
public int getVal(int [] nums, int index){
if(index < 0 || index >= nums.length) return 1;
return nums[index];
}
}
I am having the confusion in the Math.max
line. What is it nums[i]*getVal(nums, left - 1)*getVal(nums, right + 1)
?
I understand the nums[i]
part, but I do not understand the right + 1
or the left - 1
. Can someone please help explain it? I would appreciate it very much.
Imagine you want to calculate the maximum coins you can get from a sequence of balloons, lets say from
num[left]
tonum[right]
, and you start by calculating the last balloon you pop in that sequence, lets say it is ballooni
.Because it is the last balloon on that sequence, all the other balloons are already "popped", so its adjacent balloons are
num[left-1]
andnum[right+1]
So that line calculates the number of coins you get from the last balloon, plus the maximum number of coins from segment
left
toi-1
plus the maximum from segmenti+1
toright