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

更新時間: 2021 年 4 月 24 日

755 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.