forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStock_Span_Problem.cpp
More file actions
45 lines (38 loc) · 1008 Bytes
/
Stock_Span_Problem.cpp
File metadata and controls
45 lines (38 loc) · 1008 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// C++ program for a linear time solution for stock
// span problem without using stack
#include <iostream>
#include <stack>
using namespace std;
// An efficient method to calculate stock span values
// implementing the same idea without using stack
void calculateSpan(int A[], int n, int ans[])
{
// Span value of first element is always 1
ans[0] = 1;
// Calculate span values for rest of the elements
for (int i = 1; i < n; i++) {
int counter = 1;
while ((i - counter) >= 0 && A[i] >= A[i - counter]) {
counter += ans[i - counter];
}
ans[i] = counter;
}
}
// A utility function to print elements of array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above function
int main()
{
int price[] = { 10, 4, 5, 90, 120, 80 };
int n = sizeof(price) / sizeof(price[0]);
int S[n];
// Fill the span values in array S[]
calculateSpan(price, n, S);
// print the calculated span values
printArray(S, n);
return 0;
}