C++程式中的最大交替子序列和


在這個問題中,我們得到一個包含n個整數的陣列arr[]。我們的任務是建立一個程式來查詢從陣列的第一個元素開始的最大交替子序列和。

交替子序列是一個子序列,其中元素以交替的順序遞增和遞減,即先遞減,然後遞增,然後遞減。此處,反向交替子序列對於查詢最大和無效。

讓我們來看一個例子來理解這個問題:

輸入

arr[] = {5, 1, 6, 2, 4, 8, 9}

輸出

27

解釋

Starting element: 5, decrease: 1, increase: 6, decrease: 2, increase:4, N.A.
Here, we can use 4, 8, 9 as the last element of the subsequence.
Sum = 5 + 1 + 6 + 2 + 4 + 9 = 27

解決方案方法

為了解決這個問題,我們將使用動態規劃方法。為此,我們將使用兩個陣列,一個用於儲存以arr[i]結尾的元素的最大和(其中arr[i]遞增),另一個用於儲存以arr[i]結尾的元素的最大和(其中arr[i]遞減)。

然後,我們將逐個新增元素,並檢查它們是否為交替子序列。對於每個陣列,我們將計算到該索引為止的最大和,並在遍歷n個元素後返回最大值。

示例

程式說明了我們解決方案的工作原理:

 線上演示

#include<iostream>
#include<cstring>
using namespace std;
int maxVal(int x, int y){
   if(x > y)
   return x;
   return y;
}
int calcMaxSumAltSubSeq(int arr[], int n) {
   int maxSum = −10000;
   int maxSumDec[n];
   bool isInc = false;
   memset(maxSumDec, 0, sizeof(maxSumDec));
   int maxSumInc[n];
   memset(maxSumInc, 0, sizeof(maxSumInc));
   maxSumDec[0] = maxSumInc[0] = arr[0];
   for (int i=1; i<n; i++) {
      for (int j=0; j<i; j++) {
         if (arr[j] > arr[i]) {
            maxSumDec[i] = maxVal(maxSumDec[i],
            maxSumInc[j]+arr[i]);
            isInc = true;
         }
         else if (arr[j] < arr[i] && isInc)
         maxSumInc[i] = maxVal(maxSumInc[i],
         maxSumDec[j]+arr[i]);
      }
   }
   for (int i = 0 ; i < n; i++)
   maxSum = maxVal(maxSum, maxVal(maxSumInc[i],
   maxSumDec[i]));
   return maxSum;
}
int main() {
   int arr[]= {8, 2, 3, 5, 7, 9, 10};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum sum alternating subsequence starting is "<<calcMaxSumAltSubSeq(arr , n);
   return 0;
}

輸出

The maximum sum alternating subsequence starting is 25

更新於:2020年12月9日

374次瀏覽

開啟您的職業生涯

完成課程獲得認證

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