DEV Community is a community of 640,935 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Challenge Algo #5 - Almost Increasing Sequence

Given a sequence of integer as an array, determine whether it is possible to obtain a strictly increasing sequence removing no more than one element from the array.

Example

• For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false;

there is no one element in this array that can be removed in order to get a strictly increasing sequence.

• For sequence = [1, 3, 2], the output should be almostIncreasingSequence(sequence) = true;

You can remove 3 from the array to get strictly increasing sequence [1, 2]. Alternatively, you can remove 2 to get the strictly increasing sequence [1, 3].

Here we code:

``````const almostIncreasingSequence = sequence =>{
// element to remove to have increasing sequence
let count = 0;

for(let i=0; i< sequence.length; i++){

// check 1 : n is smaller or equal to n-1
if(sequence[i] <= sequence[i-1]){
count++;
// n is smaller or equal to n-2 and n+1 is smaller or equal to n-1
if(sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]){
count++;
}
}
}

// return true with 1 or no remove, otherwise false
return count <= 1;
}

console.log(almostIncreasingSequence([1,3,2,1])); // false
console.log(almostIncreasingSequence([1,3,2])); // true
console.log(almostIncreasingSequence([3,2,1])); // false
console.log(almostIncreasingSequence([1,2,3,2])); // true
``````

as usually better way or more efficient are welcome in comments...