Here is the dynamic programming definition that can be provided by someone who learned about the concept yesterday:
Quote
Dynamic programming is a recursive pattern in which the return values of a function are saved to be reused by later functions.
Calculating the value of an index in the fibonacci sequence is a perfect application for dynamic programming because each index of the Fibonacci sequence is a function of the two previous items in the sequence.
Implementation I created organically
const fibonacci = function(n, seq=[1, 1]){
if (n < 2) return 1
if (seq.length-1 < n){
seq.push(seq[seq.length-1] + seq[seq.length-2])
return fibonacci(n, seq)
}
return seq[n]
}
console.log(fibonacci(4))
Implementation I found online:
function fibonacci(n) {
// Declare the memo object once
const memo = {};
// Inner recursive function that uses the memo object
function fib(n) {
// Base cases
if (n <= 1) return n;
// Check if the value is already computed
if (memo[n]) return memo[n];
// Compute the value and store it in the memo object
memo[n] = fib(n - 1) + fib(n - 2);
return memo[n];
}
// Call the inner recursive function
return fib(n);
}
// Example usage
console.log(fibonacci(10)); // Outputs: 55
console.log(fibonacci(50)); // Outputs: 12586269025