File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Stack Algorithms/Span Problem/C++ Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Span Problem
2
+ // Here we have to find span of every element in an array, i.e number of consecutive elements before that element (including that element also)
3
+ // having values less than or equal to value of current element
4
+ // Note: Span of every element will be atleast 1
5
+
6
+
7
+ #include < iostream>
8
+ #include < stack>
9
+ using namespace std ;
10
+
11
+ // function for span problem
12
+ void spans (int *a, int n, int *span){
13
+ stack<int > s;
14
+
15
+ for (int i = 0 ; i<n; i++){
16
+ while (!s.empty () && a[i]>=a[s.top ()]){
17
+ s.pop ();
18
+ }
19
+ if (s.empty ()){
20
+ span[i] = i+1 ;
21
+ s.push (i);
22
+ }
23
+ else {
24
+ span[i] = i-s.top ();
25
+ s.push (i);
26
+ }
27
+ }
28
+
29
+ }
30
+
31
+ // testing our span function
32
+ int main (){
33
+ int a[] = {9 ,12 ,5 ,13 };
34
+ int span[4 ];
35
+ stack<int > s;
36
+ spans (a,4 ,span);
37
+ for (int i = 0 ; i<4 ; i++) cout<<span[i]<<endl;
38
+
39
+ }
You can’t perform that action at this time.
0 commit comments