C++程序:查找最长位数等差子序列的长度


假设我们有一组数字。我们需要找到最长位数等差子序列的长度。我们知道,如果一个序列先严格递增,然后严格递减,则称其为位数等差序列。严格递增序列也是位数等差序列。严格递减序列也是位数等差序列。

因此,如果输入类似于nums = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],序列大小为16,则输出为7。

为了解决这个问题,我们将遵循以下步骤:

  • 创建一个与给定数组大小相同的新数组increasingSubSeq,并将其填充为1

  • 初始化 i := 1,当 i < size 时,更新(i增加1),执行:

    • 初始化 j := 0,当 j < i 时,更新(j增加1),执行:

      • 如果 arr[i] > arr[j] 且 increasingSubSeq[i] < increasingSubSeq[j] + 1,则:

        • increasingSubSeq[i] := increasingSubSeq[j] + 1

      • 创建一个与给定数组大小相同的新数组decreasingSubSeq,并将其填充为1

    • 初始化 i := size - 2,当 i >= 0 时,更新(i减少1),执行:

      • 初始化 j := size - 1,当 j > i 时,更新(j减少1),执行:

        • 如果 arr[i] > arr[j] 且 decreasingSubSeq[i] < decreasingSubSeq[j] + 1,则:

          • decreasingSubSeq[i] := decreasingSubSeq[j] + 1

        • max := increasingSubSeq[0] + decreasingSubSeq[0] - 1

      • 初始化 i := 1,当 i < size 时,更新(i增加1),执行:

        • 如果 increasingSubSeq[i] + decreasingSubSeq[i] - 1 > max,则

          • max := increasingSubSeq[i] + decreasingSubSeq[i] - 1

        • 返回 max

让我们看看下面的实现,以便更好地理解:

示例

在线演示

#include<iostream>
using namespace std;
int longBitonicSub( int arr[], int size ) {
   int *increasingSubSeq = new int[size];
   for (int i = 0; i < size; i++)
      increasingSubSeq[i] = 1;
   for (int i = 1; i < size; i++)
      for (int j = 0; j < i; j++)
         if (arr[i] > arr[j] && increasingSubSeq[i] <
         increasingSubSeq[j] + 1)
         increasingSubSeq[i] = increasingSubSeq[j] + 1;
   int *decreasingSubSeq = new int [size];
   for (int i = 0; i < size; i++)
      decreasingSubSeq[i] = 1;
   for (int i = size-2; i >= 0; i--)
      for (int j = size-1; j > i; j--)
         if (arr[i] > arr[j] && decreasingSubSeq[i] < decreasingSubSeq[j] + 1)
decreasingSubSeq[i] = decreasingSubSeq[j] + 1;
   int max = increasingSubSeq[0] + decreasingSubSeq[0] - 1;
   for (int i = 1; i < size; i++)
      if (increasingSubSeq[i] + decreasingSubSeq[i] - 1 > max)
         max = increasingSubSeq[i] + decreasingSubSeq[i] - 1;
   return max;
}
int main() {
   int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
   int n = 16;
   cout << longBitonicSub(arr, n);
}

输入

[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15], 16

输出

7

更新于:2020年10月10日

149 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告