ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข arr เป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว
ฟังก์ชันของเราจำเป็นต้องค้นหาจำนวนลำดับที่ยาวที่สุดที่เพิ่มขึ้น (ต่อเนื่องกันหรือไม่ต่อเนื่องกัน)
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ
ป้อนข้อมูล
const arr = [2, 4, 6, 5, 8];
ผลผลิต
const output = 2;
คำอธิบายผลลัพธ์
ลำดับที่ยาวที่สุดสองลำดับต่อมาคือ [2, 4, 5, 8] และ [2, 4, 6, 8].
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [2, 4, 6, 5, 8];
const countSequence = (arr) => {
const distance = new Array(arr.length).fill(1).map(() => 1)
const count = new Array(arr.length).fill(1).map(() => 1)
let max = 1
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[i]) {
if (distance[j] <= distance[i]) {
distance[j] = distance[i] + 1
count[j] = count[i]
max = Math.max(distance[j], max)
} else if (distance[j] === distance[i] + 1) {
count[j] += count[i]
}
}
}
}
return distance.reduce((acc, d, index) => {
if (d === max) {
acc += count[index]
}
return acc
}, 0)
}
console.log(countSequence(arr)); ผลลัพธ์
2