Skip to content

Instantly share code, notes, and snippets.

@FermiDirak
Last active October 2, 2019 06:36
Show Gist options
  • Save FermiDirak/d0cfdd972f96db21bb2f889170dd82bf to your computer and use it in GitHub Desktop.
Save FermiDirak/d0cfdd972f96db21bb2f889170dd82bf to your computer and use it in GitHub Desktop.
var rob = function(nums) {
if (nums.length <= 2) {
return Math.max(...nums, 0);
}
const cache = [nums[0], nums[1]];
const dfs = (i) => {
const nextPositions = [i + 2, i + 3];
nextPositions.forEach(nextPos => {
if (nextPos > nums.length - 1) {
return;
}
const nextVal = cache[i] + nums[nextPos];
if (cache[nextPos] === undefined || nextVal > cache[nextPos]) {
cache[nextPos] = nextVal;
dfs(nextPos);
}
});
}
dfs(0);
dfs(1);
return Math.max(...cache);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment