forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
flightOfStairs.js
55 lines (43 loc) · 1.25 KB
/
flightOfStairs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*You are given positive integers n and k. You are currently at stair 0 and want to climb to stair n.
You can either climb 1, 2, or 3 stairs at a time, but you can only climb 3 stairs at most k times.
Return the number of ways to climb to the nth stair.
*/
const FlightOfStairs = (n, k) => {
const memo = new Array(n + 1);
for (let i = 0; i < n + 1; i++)
{
memo[i] = new Array(k + 1).fill(0);
}
/*passing to the utility function*/
console.log("The answer is ",solveUtil(n, k, memo));
};
const solveUtil = (n, k, memo) =>{
/*base cases*/
if (n == 0)
return 1;
else if (n < 0)
return 0;
else if (memo[n][k] != 0)
return memo[n][k];
/*calls for 1 and 2 steps*/
memo[n][k] = solveUtil(n - 1, k, memo) + solveUtil(n - 2, k, memo);
/*checking k before making calls for 3 steps*/
if (k > 0)
memo[n][k] += solveUtil(n - 3, k - 1, memo);
return memo[n][k];
};
/*taking arguments using command line arguments*/
console.log("Enter the values of n and k: ");
var arguments = process.argv;
FlightOfStairs(parseInt(arguments[2]),parseInt(arguments[3]));
/*
Input:
Enter the values of n and k:
4 1
Output:
The answer is 7
*/
/*
Time complexity: O(n*k)
Space complexity: O(n*k)
*/