Number of Valid Subarrays in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 11-Jul-2020 11:59:04
Advertisements