JavaScript 中最長的遞增序列的總數
問題
我們需要編寫一個 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP