File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
CodingBlocks Training/Day27 Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ package Lecture27 ;
2+
3+ //time complexity: O(n)
4+ // it has better space complexity than fibonacciDyanamicProg.java using recursive apporach, though time
5+ // complexity is same using DP approach.
6+
7+ public class fibonacciDPIterative {
8+
9+ public static void main (String [] args ) {
10+
11+ int nthItem = 5 ;
12+ System .out .println (fibIterative (nthItem )); // 5
13+
14+ System .out .println (fibIterative (0 )); // 0
15+ System .out .println (fibIterative (1 )); // 1
16+ System .out .println (fibIterative (6 )); // 8
17+ }
18+
19+ public static int fibIterative (int n ) {
20+ int [] memStorage = new int [n + 1 ];
21+ return fibIterative (n , memStorage );
22+ }
23+
24+ private static int fibIterative (int n , int [] storage ) {
25+ if (n == 0 || n == 1 ) {
26+ return n ;
27+ }
28+
29+ storage [0 ] = 0 ;
30+ storage [1 ] = 1 ;
31+
32+ for (int i = 2 ; i <= n ; i ++) {
33+ storage [i ] = storage [i - 1 ] + storage [i - 2 ];
34+ }
35+
36+ return storage [n ];
37+ }
38+
39+ }
You can’t perform that action at this time.
0 commit comments