Merge pull request #289 from shoaibrayeen/patch-1

Space Optimization for the code - Constant Space
This commit is contained in:
Yang Libin 2019-08-29 23:35:03 +08:00 committed by GitHub
commit 641514acb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,14 +2,16 @@
using namespace std; using namespace std;
int fib(int n) int fib(int n)
{ {
int res[n + 1]; int res[3];
res[0] = 0; res[0] = 0;
res[1] = 1; res[1] = 1;
for (int i = 2; i <= n; i++) for (int i = 2; i <= n; i++)
{ {
res[i] = res[i - 1] + res[i - 2]; res[2] = res[1] + res[0];
res[0] = res[1];
res[1] = res[2];
} }
return res[n]; return res[1];
} }
int main(int argc, char const *argv[]) int main(int argc, char const *argv[])
{ {