From 21d8937baa0198563cd545639eaa20b298c63229 Mon Sep 17 00:00:00 2001 From: Shoaib Rayeen Date: Wed, 21 Nov 2018 05:22:24 +0530 Subject: [PATCH] Optimized Version [Without Hashmap & recursion] --- Dynamic Programming/Fibonacci.java | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index b2524b4db471..d177b5bb9c5d 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -29,6 +29,10 @@ public static void main(String[] args) throws Exception { * Outputs the nth fibonacci number **/ + + + + private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); @@ -71,5 +75,35 @@ private static int fibBotUp(int n) { return fib.get(n); } + + + + /** + * This method finds the nth fibonacci number using bottom up + * + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + * + * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. + * It saves both memory and time. + * Space Complexity will be O(1) + * Time Complexity will be O(n) + * + * Whereas , the above functions will take O(n) Space. + **/ + private static int fibOptimized(int n) { + + if (n == 0) { + return 0; + } + int prev = 0 , res = 1 , next; + for ( int i = 2; i < n; i++) { + next = prev + res; + prev = res; + res = next; + } + return res; + } }