DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Ninja Training...

const ninjaTraining = (matrix, Days) => {
  // moving it to zero index days
  let day = Days - 1;
  let memo = new Map();

  const getMaxPoints = (dayIndex, lastTask) => {
    if (dayIndex === 0) {
      let maxPoint = -Infinity;
      for (let i = 0; i < 3; i++) {
        if (i !== lastTask) {
          maxPoint = Math.max(maxPoint, matrix[dayIndex][i]);
        }
      }
      return maxPoint;
    }
    if (memo.has(dayIndex + "_" + lastTask)) {
      return memo.get(dayIndex + "_" + lastTask);
    }

    let maxPoint = -Infinity;
    for (let i = 0; i < 3; i++) {
      if (i !== lastTask) {
        let point = matrix[dayIndex][i] + getMaxPoints(dayIndex - 1, i);
        maxPoint = Math.max(maxPoint, point);
      }
    }
    memo.set(dayIndex + "_" + lastTask, maxPoint);
    return maxPoint;
  };
  return getMaxPoints(day, 3);
};

console.log(
  ninjaTraining(
    [
      [1, 2, 5],
      [3, 1, 1],
      [3, 3, 3],
    ],
    3
  )
);
console.log(
  ninjaTraining(
    [
      [10, 40, 70],
      [20, 50, 80],
      [30, 60, 90],
    ],
    3
  )
);


Enter fullscreen mode Exit fullscreen mode

Top comments (0)