I am trying to count the number of ways to reach the nth stair, starting from the first stair and going up either one or two stairs at a time. The first approach below works fine, but the second does not.
//---01--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
prev2 = (prev2 + prev1) % mod;
prev1 = prev2 - prev1;
}
return prev2;
//---02--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
int curr = (prev2 + prev1) % mod;
prev1 = prev2;
prev2 = curr;
}
return prev2;
The second approach doesn't work with large n.
Sample Input Case: n = 87
Output with the second approach:
-334512466
Expected Output:
665487541
Its other way around, your first solution will overflow(not Integer overflow but negative values due to wrong logic) but not second one.
For better understanding see below updated code for your first solution -
for(int i = 2; i <= n; i++){
System.out.println("i : "+i);
prev2 = (prev2 + prev1) % mod;
System.out.println("P2 : " +prev2);
System.out.println("P1 : " +prev1);
prev1 = prev2 - prev1;
}
Below is the output of above -
i : 44
P2 : 134903163
P1 : 433494437
i : 45
P2 : -163688111
P1 : -298591274
If you observe the values you can see, for i=44, prev2 is smaller then prev1 because of mod function and when you will do prev1 = prev2 - prev1;
you will get negative value so this solution is wrong.
While second solution will work as there is no such case.