用 C++ 統計滿足給定條件的索引對
給定一個前 N 個自然數的排列陣列。目標是找到滿足以下條件的元素的索引對:
如果陣列為 Arr[],則 i、j 為索引,統計滿足 Arr[i]+Arr[j]=max(Arr[x])(其中 i<=x<=j)的元素對。
也就是說,Arr[i] 和 A[j] 的和等於這兩個片段之間出現的最大元素。
輸入
Arr[]= { 2,4,1,3,6,5 }輸出
Count of index pairs which satisfy the given condition:1
解釋 - 給出的是對的和:
2+4=6,6 是最大值,但不在 2 和 4 之間。
2+1=3,3 不在 2 和 1 之間,它們之間最大值為 4。
2+3=5,5 不在 2 和 3 之間,它們之間最大值為 4。
2+6=8,8 不在 2 和 6 之間,它們之間最大值為 4。
類似地
1+5=6,6 在 1 和 5 之間,它們之間最大值為 6。
在所有這些中,只有一對滿足條件。
輸入
Arr[]= { 1,2,5,4,3 }輸出
Count of index pairs which satisfy the given condition:2
解釋 - 給出的是對的和:
1+5=6,6 是最大值,但不在 1 和 5 之間。
1+4=5,5 在 1 和 4 之間,它們之間最大值為 5。
2+3=5,5 在 2 和 3 之間,它們之間最大值為 5。
1+3=4,4 在 1 和 3 之間,但它們之間最大值為 5。
在所有這些中,有兩對滿足條件。
下面程式中使用的方案如下
整數陣列 Arr[] 儲存數字,其長度為 size。
函式 countPairs(int A[],int n) 以陣列及其大小 n 作為輸入,並返回滿足上述條件的對的個數。
變數 count 用於儲存此類對的初始值 0。
將 max1 初始化為第一個元素,並將 maxindex 中的索引初始化為 0,以儲存迄今為止找到的最大值及其索引。
使用 for 迴圈開始遍歷陣列。
在巢狀的 for 迴圈內,如果給定的 A[j]>=max1,則用 j 更新 max1 及其索引。
對於 A[i] 和 A[j] 的每一對,如果和等於 max1 且索引 maxindex 在 i 和 j 之間,則遞增 count,因為條件滿足。
在兩個迴圈結束後,返回 count 中的結果。
示例
// CPP implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Function to return the count of
// required index pairs
int countPairs(int A[], int n){
// To store the required count
int count = 0;
int i,j,k;
int max1=A[0];
int maxindex=0;
for ( i = 0; i<n-1; i++){
for(j=i+1;j<n;j++){
if(A[j]>=max1){
max1=A[j];
maxindex=j;
}
if(A[i]+A[j]==max1 && maxindex>=i && maxindex<=j)
count++;
}
}
// Return count of subsegments
return count;
}
int main(){
int Arr[] = {3, 4, 6, 1, 5, 2};
int size =6;
cout <<endl<<"Count of index pairs which satisfy the given condition:"
<<countPairs(Arr,size);
return 0;
}輸出
Count of index pairs which satisfy the given condition: 1
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP