Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get almost increasing sequence of integers

Tags:

javascript

Given a sequence of integers as an array,i have to determine whether it is possible to obtain a strictly increasing sequence by 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

We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].

The function must return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.

Here is what i have already tried , but it doesnt work for all situations

function almostIncreasingSequence(sequence) {
    for (var i = 0; i < sequence.length; i++) {
        if (sequence[i] > sequence[i + 1]) {
            sequence.splice(i, 1);
           return true;
        };
        return false;
    };
}
like image 851
Norayr Ghukasyan Avatar asked Sep 27 '17 10:09

Norayr Ghukasyan


People also ask

What is almost increasing sequence?

That is, given a constant , a sequence S = 〈 s 1 , s 2 , … , s k 〉 is said to be almost increasing if and only if s i > max 1 ≤ j < i ⁡ s j − c for all 1 < i ≤ k .

What is strictly increasing sequence?

It is a mathematical term that represents an arrangement of numbers where every succeeding number is greater than its preceding number. Other than this there exists increasing sequence where the succeeding element is greater than or equal to the preceding element.


1 Answers

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;
}
like image 83
Vipin PS Avatar answered Sep 28 '22 00:09

Vipin PS