查詢 C++ 中嚴格遞減子陣列的計數


假設我們有一個數組 A。我們必須找出長度> 1 的所有嚴格遞減子陣列的總數。所以如果 A = [100, 3, 1, 15]。所以遞減序列為 [100, 3]、[100, 3, 1]、[15]。所以輸出為 3。因為找到了三個子陣列。

這個想法是,找出長度為 l 的子陣列,並將 l(l – 1)/2 新增到結果中。

範例

 現場演示

#include<iostream>
using namespace std;
int countSubarrays(int array[], int n) {
   int count = 0;
   int l = 1;
   for (int i = 0; i < n - 1; ++i) {
      if (array[i + 1] < array[i])
         l++;
      else {
         count += (((l - 1) * l) / 2);
         l = 1;
      }
   }
   if (l > 1)
   count += (((l - 1) * l) / 2);
   return count;
}
int main() {
   int A[] = { 100, 3, 1, 13, 8};
   int n = sizeof(A) / sizeof(A[0]);
   cout << "Number of decreasing subarrys: " << countSubarrays(A, n);
}

輸出

Number of decreasing subarrys: 4

更新於: 2019 年 12 月 19 日

206 次觀看

成就你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.