Created
April 15, 2017 19:55
-
-
Save ryanSN/8444805f6085e7c37a8e0c6c29dafec6 to your computer and use it in GitHub Desktop.
Javascript almost increasing sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function almostIncreasingSequence(sequence) { | |
var found = false; | |
for (var i=0;i<sequence.length;i++) { | |
if(sequence[i] <= sequence[i-1]) { | |
if(found) { | |
return false; | |
} | |
found = true; | |
if(i === 1 || i + 1 === sequence.length) { | |
continue; | |
} | |
else if (sequence[i] > sequence[i-2]) { | |
sequence[i-1] = sequence[i-2]; | |
} | |
else if(sequence[i-1] >= sequence[i+1]) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} |
Could you please explain your solution?
Thank you so much!
@dohoangdinhtien I believe the sequence is not almost increasing if there is more than one number that is less than its previous number. Hence the solution above
Great!!!
function almostIncreasingSequence(sequence: number[]): boolean {
var isFirst = true;
for (var i = 0; i < sequence.length; i++) {
if (sequence[i] >= sequence[i+1]) {
if (isFirst) {
isFirst = false;
if (sequence[i-1] >= sequence[i+1] && sequence[i] >= sequence[i+2])
{
return false;
}
}
else return false;
}
}
return true;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, it works :)