
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Number of Valid Subarrays in C++
Suppose we have an array A of integers, we have to find the number of non-empty continuous subarrays that satisfy this condition: The leftmost element of the subarray is not larger than other elements in the subarray.
So, if the input is like [1,4,2,5,3], then the output will be 11, as there are 11 valid subarrays, they are like [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
To solve this, we will follow these steps −
ret := 0
n := size of nums
Define one stack st
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
x := nums[i]
while (not st is empty and x < top element of st), do −
delete element from st
insert x into st
ret := size of st + ret
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int validSubarrays(vector<int>& nums) { int ret = 0; int n = nums.size(); stack <int> st; for(int i = 0; i < nums.size(); i++){ int x = nums[i]; while(!st.empty() && x < st.top()) st.pop(); st.push(x); ret += st.size(); } return ret; } }; main(){ Solution ob; vector<int> v = {1,4,2,5,3}; cout << (ob.validSubarrays(v)); }
Input
{1,4,2,5,3}
Output
11
- Related Articles
- Count Number of Nice Subarrays in C++
- Valid Number in Python
- Number of Subarrays with Bounded Maximum in C++
- Valid Triangle Number in C++
- Count the number of non-increasing subarrays in C++
- Find number of subarrays with even sum in C++
- Program to count number of nice subarrays in Python
- Number of Valid Words for Each Puzzle in C++
- Maximize the number of subarrays with XOR as zero in C++
- Program to count number of valid triangle triplets in C++
- Find the Number of Subarrays with Odd Sum using C++
- Count subarrays with equal number of occurrences of two given elements in C++
- Find the Number Of Subarrays Having Sum in a Given Range in C++
- Find the number of subarrays have bitwise OR >= K using C++
- Find the Number of Subarrays with m Odd Numbers using C++
