Table of Contents
How to solve
Example
Output
Explanation of the above code
Efficient method
Description of the above code
Conclusion
Home Backend Development C++ Write a code using C++ to find the number of subarrays with the same minimum and maximum values

Write a code using C++ to find the number of subarrays with the same minimum and maximum values

Aug 25, 2023 pm 11:33 PM
quantity maximum value minimum value c programming subarray

Write a code using C++ to find the number of subarrays with the same minimum and maximum values

In this article, we will use C to solve the problem of finding the number of subarrays with the same maximum and minimum values. Following is an example of this problem −

Input : array = { 2, 3, 6, 6, 2, 4, 4, 4 }
Output : 12
Explanation : {2}, {3}, {6}, {6}, {2}, {4}, {4}, {4}, {6,6}, {4,4}, {4,4} and { 4,4,4 } are the subarrays which can be formed with maximum and minimum element same.

Input : array = { 3,3,1,5,1,2,2 }
Output : 9
Explanation : {3}, {3}, {1}, {5}, {1}, {2}, {2}, {3,3} and {2,2} are the subarrays which can be formed with minimum and maximum are the same.
Copy after login

How to solve

By example, we can say that a minimum number of subarrays can be formed using the same minimum and maximum elements equal to the size of the array. The number of subarrays can be greater if consecutive numbers are the same.

So we can use the method of traversing each element and checking whether its consecutive numbers are the same. If the consecutive numbers are the same, the count will be increased. If different numbers are found, the inner loop will be interrupted.

Every time the inner loop ends or is interrupted, the result variable will be incremented, and finally the result variable will be displayed.

p>

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
    int a[ ] = { 2, 4, 5, 3, 3, 3 };
    int n = sizeof(a) / sizeof(a[0]);
        int result = n, count =0;
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            if(a[i]==a[j])
                count++;
            else
                break;
        }
        result+=count;
        count =0;
    }
    cout << "Number of subarrays having minimum and maximum elements same:" << result;
    return 0;
}
Copy after login

Output

Number of subarrays having minimum and maximum elements same: 9
Time complexity = O(n<sup>2</sup>).
Copy after login

Explanation of the above code

In this code, we use the variable n to store the array The size of , result = n, since at least n subarrays can be formed and counts of the same number calculated.

The outer loop is used to process each element in the array. The inner loop is used to find how many consecutive identical numbers there are after the index element and at the end of the inner loop it increments the count variable along with the result variable. Finally the output stored in the result variable is displayed.

Efficient method

In this method, we iterate through each element, and for each element, we search how many consecutive identical numbers there are. For each identical number found, we increment the count variable and when a different number is found, find how many subdivisions can be formed using this formula by using the formula "n = n*(n 1)/2" array and increment the result variable.

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
    int a[] = { 2, 4, 5, 3, 3, 3 };
    int n = sizeof(a) / sizeof(a[0]);
        int result = 0;
    int count =1,temp=a[0];
    for (int i = 1; i < n; i++) {
        if (temp==a[i]){
            count++;
        }
        else{
            temp=a[i];
            result = result + (count*(count+1)/2);
            count=1;
        }
    }
    result = result + (count*(count+1)/2);
    cout <<  "Number of subarrays having minimum and maximum elements same:" << result;
    return 0;
}
Copy after login

Output

Number of subarrays having minimum and maximum elements same: 9
Time complexity : O(n)
Copy after login

Description of the above code

In this code, we store the 0th index of the array in the temp variable, And start looping from index 1. We check if the temp variable is equal to the element at the current index and increment the count by 1 for the same number found. If the temp variable is not equal to the index element, we find the combination of subarrays that can be derived by counting the same number and store the result in the result variable. We change the temporary value to the current index, resetting the count to 1. Finally, we display the answer stored in the result variable.

Conclusion

In this article, we solved the problem of finding the number of subarrays with the same minimum and maximum elements. We also learned a C program to solve this problem and a complete way to solve this problem (normal and efficient). We can write the same program in other languages ​​such as C, java, python and other languages. Hope this article is helpful to you.

The above is the detailed content of Write a code using C++ to find the number of subarrays with the same minimum and maximum values. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use math.Max ​​function to get the maximum value in a set of numbers Use math.Max ​​function to get the maximum value in a set of numbers Jul 24, 2023 pm 01:24 PM

Use the math.Max ​​function to obtain the maximum value in a set of numbers. In mathematics and programming, it is often necessary to find the maximum value in a set of numbers. In Go language, we can use the Max function in the math package to achieve this function. This article will introduce how to use the math.Max ​​function to obtain the maximum value in a set of numbers, and provide corresponding code examples. First, we need to import the math package. In the Go language, you can use the import keyword to import a package, as shown below: import"mat

OpenOOD update v1.5: Comprehensive and accurate out-of-distribution detection code library and testing platform, supporting online rankings and one-click testing OpenOOD update v1.5: Comprehensive and accurate out-of-distribution detection code library and testing platform, supporting online rankings and one-click testing Jul 03, 2023 pm 04:41 PM

Out-of-distribution (OOD) detection is crucial for the reliable operation of open-world intelligent systems, but current object-oriented detection methods suffer from "evaluation inconsistencies" (evaluation inconsistencies). Previous work OpenOODv1 unifies the evaluation of OOD detection, but still has limitations in scalability and usability. Recently, the development team once again proposed OpenOODv1.5. Compared with the previous version, the new OOD detection method evaluation has been significantly improved in ensuring accuracy, standardization and user-friendliness. Image Paper: https://arxiv.org/abs/2306.09301OpenOODCodebase:htt

Increase your knowledge! Machine learning with logical rules Increase your knowledge! Machine learning with logical rules Apr 01, 2023 pm 10:07 PM

On the precision-recall curve, the same points are plotted with different axes. Warning: The first red dot on the left (0% recall, 100% precision) corresponds to 0 rules. The second dot on the left is the first rule, and so on. Skope-rules uses a tree model to generate rule candidates. First build some decision trees and consider the paths from the root node to internal nodes or leaf nodes as rule candidates. These candidate rules are then filtered by some predefined criteria such as precision and recall. Only those with precision and recall above their thresholds are retained. Finally, similarity filtering is applied to select rules with sufficient diversity. In general, Skope-rules are applied to learn the root cause of each

Use C++ to write code to find the Nth non-square number Use C++ to write code to find the Nth non-square number Aug 30, 2023 pm 10:41 PM

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

In C programming, find the area of ​​a circle In C programming, find the area of ​​a circle Aug 25, 2023 pm 10:57 PM

A circle is a closed figure. All points on a circle are equidistant from a point inside the circle. The center point is called the center of the circle. The distance from a point to the center of a circle is called the radius. Area is a quantitative representation of the span of dimensions of a closed figure. The area of ​​a circle is the area enclosed within the dimensions of the circle. The formula to calculate the area of ​​a circle, Area=π*r*r To calculate the area, we give the radius of the circle as input, we will use the formula to calculate the area, algorithm STEP1: Takeradiusasinputfromtheuserusingstdinput.STEP2: Calculatetheareaofcircleusing, area=(

Inversion algorithm for right rotation of array written in C++ Inversion algorithm for right rotation of array written in C++ Sep 08, 2023 pm 08:17 PM

In this article, we will learn about the reversal algorithm to rotate a given array to the right by k elements, for example −Input:arr[]={4,6,2,6,43,7,3,7},k= 4Output:{43,7,3,7,4,6,2,6}Explanation:Rotatingeachelementofarrayby4-elementtotherightgives{43,7,3,7,4,6,2,6}.Input:arr[]={8 ,5,8,2,1,4,9,3},k=3Output:{4,9,3,8,5,8,2,1} Find the solution

How to find the number of parameters provided by runtime in Java? How to find the number of parameters provided by runtime in Java? Sep 23, 2023 pm 01:13 PM

In Java, one way to pass parameters at runtime is to use the command line or terminal. When retrieving these values ​​for command line parameters, we may need to find the number of parameters provided by the user at runtime, which can be achieved with the help of the length attribute. This article aims to explain the process of passing and getting a user-supplied number of parameters with the help of a sample program. Get the number of arguments provided by the user at run time Before finding the number of command line arguments, our first step is to create a program that allows the user to pass arguments at run time. String[] parameter When writing Java programs, we often encounter the main() method. When the JVM calls this method, the Java application starts executing. It is used with an argument called String[]args

Linux command: How to check the number of telnet processes Linux command: How to check the number of telnet processes Mar 01, 2024 am 11:39 AM

Linux commands are one of the indispensable tools in the daily work of system administrators. They can help us complete various system management tasks. In operation and maintenance work, sometimes it is necessary to check the number of a certain process in the system in order to detect problems and make adjustments in time. This article will introduce how to use Linux commands to check the number of telnet processes, let us learn together. In Linux systems, we can use the ps command combined with the grep command to view the number of telnet processes. First, we need to open a terminal,

See all articles