// Arup Guha
// 11/10/2026
// Fibonacci code to introduce memoization and dynamic programming

import java.util.*;

public class dp_intro {
	
	public static void main(String[] args) {
	
		// Slow way!
		long start = System.currentTimeMillis();
		long res = fib(47);
		long end = System.currentTimeMillis();
		System.out.println("47th fib is "+res+" took "+(end-start)+" ms.");
		
		// Memoization solution.
		start = System.currentTimeMillis();
		long[] memo = new long[48];
		Arrays.fill(memo, -1);
		long res2 = fib_memo(47, memo);
		end = System.currentTimeMillis();
		System.out.println("memo 47th fib is "+res2+" took "+(end-start)+" ms.");
		
		// DP solution.
		start = System.currentTimeMillis();
		long res3 = fib_dp(47);
		end = System.currentTimeMillis();
		System.out.println("memo 47th fib is "+res3+" took "+(end-start)+" ms.");
	}

	// CS1 Style recursion for Fibonacci...
	public static long fib(int n) {
		if (n<2) return n;
		return fib(n-1)+fib(n-2);
	}
	
	// Modify recursive solution so that it doesn't make redundant method calls
	// storing answers to old calls in the memo array.
	public static long fib_memo(int n, long[] memo) {
		
		// Same base case.
		if (n<2) return n;
		
		// We did this before.
		if (memo[n] != -1) return memo[n];
		
		// Solve the problem, but before you return the answer, store the
		// answer in the table.
		return memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo);
	}
	
	// Traditional Dynamic Programming.
	public static long fib_dp(int n) {
		
		// Create memory to store answers.
		long[] f = new long[n+1];
		
		// Seed necessary answers to get the ball rolling, usually base cases
		// from recursion. Note that f[0] = 0 already...
		f[1] = 1;
		
		// Store each answer using the recursive breakdown, but now, the answers
		// we need are already stored in the array. So we do this bottom-up
		// typically.
		for (int i=2; i<=n; i++)
			f[i] = f[i-1] + f[i-2];
		
		// Ta da!
		return f[n];
	}
}