Removing least number of elements to convert array into increasing sequence using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function should try and remove the least number of elements from the array so that the array becomes an increasing sequence.

Example

Following is the code −

 Live Demo

const arr = [1, 100, 2, 3, 100, 4, 5];
const findIncreasingArray = (arr = []) => {
   const copy = arr.slice();
   for(let i = 0; i < copy.length; i++){
      const el = arr[i];
      const next = arr[i + 1];
      if(el > next){
         copy[i] = undefined;
      };
   };
   return copy.filter(Boolean);
};
console.log(findIncreasingArray(arr));

Output

[ 1, 2, 3, 4, 5 ]

Updated on: 19-Apr-2021

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements