File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -29,6 +29,10 @@ public static void main(String[] args) throws Exception {
29
29
* Outputs the nth fibonacci number
30
30
**/
31
31
32
+
33
+
34
+
35
+
32
36
private static int fibMemo (int n ) {
33
37
if (map .containsKey (n )) {
34
38
return map .get (n );
@@ -71,5 +75,35 @@ private static int fibBotUp(int n) {
71
75
72
76
return fib .get (n );
73
77
}
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
+ }
74
108
}
75
109
You can’t perform that action at this time.
0 commit comments