Skip to content

Commit

Permalink
✨ Add the 2nd solution, an enhancement of the before one
Browse files Browse the repository at this point in the history
  • Loading branch information
mohanadft committed Sep 7, 2023
1 parent a83af48 commit 3410749
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/frog-jump/solutions/memoization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,36 @@ const fragJump1 = (n: number, heights: number[]): number => {

return Math.min(jumpOne, jumpTwo);
};

/**
* An Optimized Solution of the above.
*
* @param {number} n
* @param {number[]} heights
* @param {number[]} dp
* @returns {number}
*/

const fragJump2 = (
n: number,
heights: number[],
dp: number[] = Array(n + 1).fill(-1)
): number => {
if (n === 0) {
return 0;
}

if (dp[n] !== -1) return dp[n];

let jumpOne =
fragJump2(n - 1, heights, dp) + Math.abs(heights[n] - heights[n - 1]);
let jumpTwo = Infinity;

if (n > 1) {
jumpTwo =
fragJump2(n - 2, heights, dp) + Math.abs(heights[n] - heights[n - 2]);
}

dp[n] = Math.min(jumpOne, jumpTwo);
return dp[n];
};

0 comments on commit 3410749

Please sign in to comment.