var maxCoins = (nums) => {
const _nums = [ 1, ...nums, 1 ];
return search(_nums);
}
var search = (nums, left = 1 , right = (nums.length - 2), memo = initMemo(nums)) => {
const isBaseCase = (right - left < 0);
if (isBaseCase) return 0;
const hasSeen = (memo[left][right] !== -1);
if (hasSeen) return memo[left][right];
return dfs(nums, left, right, memo);
}
var initMemo = (nums) => new Array(nums.length).fill()
.map(() => new Array(nums.length).fill(-1));
var dfs = (nums, left, right, memo, result = 0) => {
for (let i = left; (i <= right); i++) {
const gain = ((nums[left - 1] * nums[i]) * nums[right + 1]);
const _left = search(nums, left, (i - 1), memo);
const _right = search(nums, (i + 1), right, memo);
const remaining = (_left + _right);
result = Math.max(result, remaining + gain);
}
memo[left][right] = result;
return result;
}
var maxCoins = (nums) => {
const tabu = initTabu(nums);
search(nums, tabu);
return tabu[1][(nums.length)];
}
var initTabu = (nums) => new Array(nums.length + 2).fill()
.map(() => new Array(nums.length + 2).fill(0))
var search = (nums, tabu) => {
const _nums = [ 1, ...nums, 1 ];
for (let left = nums.length; (1 <= left); left--) {
for (let right = left; (right <= nums.length); right++) {
for (let i = left; (i <= right); i++) {
const gain = ((_nums[left - 1] * _nums[i]) * _nums[right + 1]);
const remaining = (tabu[left][i - 1] + tabu[i + 1][right]);
tabu[left][right] =
Math.max(remaining + gain, tabu[left][right]);
}
}
}
}