DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Robber I & II


/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  let memo = new Map();
  const getAllAdjacentPermutation = (index) => {
    if (index === 0) {
      return nums[index];
    }
    if (index < 0) {
      return 0;
    }
    if (memo.has(index)) {
      return memo.get(index);
    }
    // pick & not pick
    let pick = nums[index] + getAllAdjacentPermutation(index - 2);
    let notPick = 0 + getAllAdjacentPermutation(index - 1);
    memo.set(index, Math.max(pick, notPick));
    return memo.get(index);
  };
  return getAllAdjacentPermutation(nums.length - 1);
};

// console.log(rob([1, 2, 3, 1]));
console.log(rob([1, 2, 3]));

Enter fullscreen mode Exit fullscreen mode
/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (num) {
  let memo = new Map();
  let withoutFirst = num.slice(1);
  let withoutLast = num.slice(0, -1);

  if (num.length === 1) {
    return num[0];
  }

  const getAllAdjacentPermutation = (index, nums) => {
    if (index === 0) {
      return nums[index];
    }
    if (index < 0) {
      return 0;
    }
    if (memo.has(index)) {
      return memo.get(index);
    }
    // pick & not pick
    let pick = nums[index] + getAllAdjacentPermutation(index - 2, nums);
    let notPick = 0 + getAllAdjacentPermutation(index - 1, nums);
    memo.set(index, Math.max(pick, notPick));
    return memo.get(index);
  };

  let wthoutFirstMax = getAllAdjacentPermutation(
    withoutFirst.length - 1,
    withoutFirst
  );
  memo = new Map();
  let wthoutLastMax = getAllAdjacentPermutation(
    withoutLast.length - 1,
    withoutLast
  );

  return Math.max(wthoutFirstMax, wthoutLastMax);
};

console.log(rob([1, 2, 3, 1]));
console.log(rob([1]));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)