Skip to content

Commit 9ac05d1

Browse files
Merge pull request #208 from mohitmo/master
Added Span Problem under Stack Algorithms
2 parents 0297ed1 + 720994c commit 9ac05d1

File tree

1 file changed

+39
-0
lines changed
  • Stack Algorithms/Span Problem/C++

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)