Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Dynamic Programming/Fibonacci.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
}