Skip to content

Commit 21d8937

Browse files
author
Shoaib Rayeen
authored
Optimized Version [Without Hashmap & recursion]
1 parent 819b7fd commit 21d8937

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Dynamic Programming/Fibonacci.java

+34
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ public static void main(String[] args) throws Exception {
2929
* Outputs the nth fibonacci number
3030
**/
3131

32+
33+
34+
35+
3236
private static int fibMemo(int n) {
3337
if (map.containsKey(n)) {
3438
return map.get(n);
@@ -71,5 +75,35 @@ private static int fibBotUp(int n) {
7175

7276
return fib.get(n);
7377
}
78+
79+
80+
81+
/**
82+
* This method finds the nth fibonacci number using bottom up
83+
*
84+
* @author Shoaib Rayeen (https://github.com/shoaibrayeen)
85+
* @param n The input n for which we have to determine the fibonacci number
86+
* Outputs the nth fibonacci number
87+
*
88+
* This is optimized version of Fibonacci Program. Without using Hashmap and recursion.
89+
* It saves both memory and time.
90+
* Space Complexity will be O(1)
91+
* Time Complexity will be O(n)
92+
*
93+
* Whereas , the above functions will take O(n) Space.
94+
**/
95+
private static int fibOptimized(int n) {
96+
97+
if (n == 0) {
98+
return 0;
99+
}
100+
int prev = 0 , res = 1 , next;
101+
for ( int i = 2; i < n; i++) {
102+
next = prev + res;
103+
prev = res;
104+
res = next;
105+
}
106+
return res;
107+
}
74108
}
75109

0 commit comments

Comments
 (0)