-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0842-split-array-into-fibonacci-sequence.js
More file actions
63 lines (51 loc) · 1.48 KB
/
0842-split-array-into-fibonacci-sequence.js
File metadata and controls
63 lines (51 loc) · 1.48 KB
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
56
57
58
59
60
61
62
63
/**
* Split Array Into Fibonacci Sequence
* Time Complexity: O(N * M^2)
* Space Complexity: O(K)
*/
var splitIntoFibonacci = function (numInput) {
const foundSequence = [];
const maximumValue = 2 ** 31 - 1;
const exploreCombinations = (currentStartIndex) => {
if (currentStartIndex === numInput.length && foundSequence.length >= 3) {
return true;
}
for (
let segmentLength = 1;
segmentLength <= numInput.length - currentStartIndex;
segmentLength++
) {
if (numInput[currentStartIndex] === "0" && segmentLength > 1) {
break;
}
const currentSegmentValue = parseInt(
numInput.substring(
currentStartIndex,
currentStartIndex + segmentLength,
),
);
if (currentSegmentValue > maximumValue) {
break;
}
if (foundSequence.length >= 2) {
const secondPreviousElement = foundSequence[foundSequence.length - 2];
const previousElement = foundSequence[foundSequence.length - 1];
const expectedSum = secondPreviousElement + previousElement;
if (currentSegmentValue > expectedSum) {
break;
}
if (currentSegmentValue < expectedSum) {
continue;
}
}
foundSequence.push(currentSegmentValue);
if (exploreCombinations(currentStartIndex + segmentLength)) {
return true;
}
foundSequence.pop();
}
return false;
};
exploreCombinations(0);
return foundSequence;
};