StanimirPavlov 4 Точки

## 5. Extract an Non-decreasing Subsequence from an Array - Javascript

Здравейте,

На задача 5. Extract an Non-decreasing Subsequence from an Array не мога да извадя повече от 60/100. Условие:

Write a JS function that extracts only those numbers that form a non-decreasing subsequence. In other words, you start from the first element and continue to the end of the given array of numbers. Any number which is LESS THAN the current biggest one is ignored, alternatively if it’s equal or higher than the current biggest one you set it as the current biggest one and you continue to the next number.

The input comes as array of strings. Each element will represent a number.

The output is the processed array after the filtration, which should be a non-decreasing subsequence. Each element should be printed on a new line.

Предварително благодаря

Тагове:
1
Pittyr 2 Точки

Макар и поста да е от 2017 задачата все още я има в More Exercise, затова реших да споделя няколко решения, които могат да помогнат на някой.

1. Решение с filter

``````function solve(array) {
let max = Number.MIN_SAFE_INTEGER;
let arr = array.filter(num => {
if (num > max) {
max = num;
return true;
} else {
return false;
}
});

console.log(arr.join(" "));
};``````

2. Решение с filter и допълнителна фунция

``````function solve(array) {
let max = Number.MIN_SAFE_INTEGER;
let arr = array.filter(filterMaxNum);

function filterMaxNum(num) {
if (num >= max) {
max = num;
return true;
}
return false;
}

console.log(arr.join(" "));
};``````

3. Решение с for и push

``````function solve(array) {
let newArr = [];
let max = Number.MIN_SAFE_INTEGER;

for (let i = 0; i < array.length; i++) {
if (array[i] >= max) {
max = array[i];
newArr.push(array[i]);
}
}

console.log(newArr.join(" "));
};``````

0