เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม ฟังก์ชันควรคืนค่าความยาวของลำดับลดลงที่ยาวที่สุดจากอาร์เรย์
เช่น ถ้าอาร์เรย์อินพุตคือ:
const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];
ผลลัพธ์ควรเป็น:
const output = 4;
เพราะลำดับลดลงที่ยาวที่สุด (ของคำที่ติดกัน) คือ [5, 4, 3, 2]
ตัวอย่าง
const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];
const decreasingSequence = (arr = []) => {
let longest = [];
let curr = [];
const setDefault = (newItem) => {
if (curr.length > longest.length) { longest = curr; }
curr = [newItem];
};
for (const item of arr) {
if (curr.length && item > curr[curr.length - 1]) {
setDefault(item);
} else {
curr.push(item);
}
}
setDefault();
return longest.length;
};
console.log(decreasingSequence(arr));
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังนี้:
4