Almost Increasing Sequence
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.
Example
almost_increasing_sequence(sequence) = falseThere 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 bealmost_increasing_sequence(sequence) = trueYou can remove
3from the array to get the strictly increasing sequence[1, 2]. Alternately, you can remove2to get the strictly increasing sequence[1, 3].
Solution
py
def almost_increasing_sequence(sequence):
droppped = False
last = prev = min(sequence) - 1
for elm in sequence:
if elm <= last:
if droppped:
return False
else:
droppped = True
if elm <= prev:
prev = last
elif elm >= prev:
prev = last = elm
else:
prev, last = last, elm
return Truejs
function almostIncreasingSequence(sequence) {
let count = 0;
for (let i = 0; i < sequence.length; i++) {
if (sequence[i] <= sequence[i - 1]) {
count++;
if (sequence[i] <= sequence[i - 2] && sequence[i + 1] <= sequence[i - 1]) {
return false;
}
}
}
return count <= 1;
}
console.log(almostIncreasingSequence([1, 3, 2]));