
在本文中,我们需要找到给定序列中大于给定数字X的段或子数组的数量。
我们只能计算重叠的段一次,相邻的两个元素或段不应单独计数。因此,这里是给定问题的基本示例−
Input : arr[ ] = { 9, 6, 7, 11, 5, 7, 8, 10, 3}, X = 7
Output : 3
Explanation : { 9 }, { 11 } and { 8, 10 } are the segments greater than 7
Input : arr[ ] = { 9, 6, 12, 2, 11, 14, 8, 14 }, X = 8
Output : 4
Explanation : { 9 }, { 12 }, { 11, 14 } and { 14 } are the segments greater than 8
寻找解决方案的方法
天真的方法
在这个问题中,我们用 0 初始化变量state并开始处理给定的数组,当找到大于 X 的元素时,将状态更改为 1,并继续处理元素;当找到小于或等于 X 的数字时,将状态更改回 0,每次状态变为 1 并返回时,将 count 增加 1到 0。
示例
#include <bits/stdc++.h>
using namespace std;
int main (){
int a[] = { 9, 6, 12, 2, 11, 14, 8, 14 };
int n = sizeof (a) / sizeof (a[0]);
int X = 8;
int state = 0;
int count = 0;
// traverse the array
for (int i = 0; i < n; i++){
// checking whether element is greater than X
if (a[i] > X){
state = 1;
}
else{
// if flag is true
if (state)
count += 1;
state = 0;
}
}
// checking for the last segment
if (state)
count += 1;
cout << "Number of segments where all elements are greater than X: " << count;
return 0;
}
输出
Number of segments where all elements are greater than X: 4
上述程序说明
在上面的程序中,我们使用状态作为开关,当找到大于 X 的数字时将其设置为 1,当找到大于 X 的数字时将其设置为 0找到小于或等于 X 的数字,每次状态变为 1 并返回到 0 时,我们将计数加 1。最后,打印存储在计数中的结果。
结论 h2>
在本文中,我们通过应用每当找到段时将状态设置为 1 和 0 &
.........................................................