Find the Number of segments where all elements are greater than X using C++

C++Server Side ProgrammingProgramming

In this article, we have to find the number of segments or subarrays in a given sequence where elements greater than the given number X.

We can count overlapping segments only once, and two contiguous elements or segments should not count separately. So here is the basic example of the given problem −

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

Approach to Find the Solution

Naive Approach

In this problem, we are initializing a variable state with 0 and begin processing the given array and change the state to 1 when an element greater than X is found and keep on processing the elements and change the state back to 0 when number less than or equal to X is found and increment count with 1 for every time state goes to 1 and back to 0.

Example

#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;
}

Output

Number of segments where all elements are greater than X: 4

Explanation of the Above Program

In the above program, we are using the state as a switch, and we set it to 1 when a number greater than X is found and set it to 0 when a number less than or equal to X is found, and for every time state goes to 1 and comes back to 0 we increment the count by 1. Finally, printing the result stored in the count.

Conclusion

In this article, we solve the problem of finding the number of segments where all elements are greater than X by applying an approach of setting the state to 1 and 0 whenever a segment is found. We can write this program in any other programming language like C, Java, Python, etc.

raja
Published on 24-Nov-2021 11:22:10
Advertisements