Update fibonacci-solution.js

Better O(n) time
This commit is contained in:
cats256 2023-07-04 12:07:04 -05:00 committed by GitHub
parent 5a7cd9b162
commit 76551b0e8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 6 deletions

View File

@ -1,10 +1,17 @@
const fibonacci = function(count) {
if (count < 0) return "OOPS"
const fibPart = [0, 1];
for (let index = 1; index < count; index++) {
fibPart.push(fibPart[index] + fibPart[index -1]);
if (count < 0) return "OOPS";
if (count === 0) return 0;
let first_prev = 1;
let second_prev = 0;
for (let i = 2; i <= count; i++) {
let curr = first_prev + second_prev;
second_prev = first_prev;
first_prev = curr;
}
return fibPart[count];
return first_prev;
};
module.exports = fibonacci;