Open In App

The Stock Span Problem

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The stock span problem is a financial problem where we have a series of N daily price quotes for a stock and we need to calculate the span of the stock’s price for all N days. The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. 

Examples:

Input: N = 7, price[] = [100 80 60 70 60 75 85]
Output: 1 1 1 2 1 4 6
Explanation: Traversing the given input span for 100 will be 1, 80 is smaller than 100 so the span is 1, 60 is smaller than 80 so the span is 1, 70 is greater than 60 so the span is 2 and so on. Hence the output will be 1 1 1 2 1 4 6.

Input: N = 6, price[] = [10 4 5 90 120 80]
Output:1 1 2 4 5 1
Explanation: Traversing the given input span for 10 will be 1, 4 is smaller than 10 so the span will be 1, 5 is greater than 4 so the span will be 2 and so on. Hence, the output will be 1 1 2 4 5 1.

 

Naive Approach: To solve the problem follow the below idea:

Traverse the input price array. For every element being visited, traverse elements on the left of it and increment the span value of it while elements on the left side are smaller

Below is the implementation of the above approach:

C++




// C++ program for brute force method
// to calculate stock span values
#include <bits/stdc++.h>
using namespace std;
 
// Fills array S[] with span values
void calculateSpan(int price[], int n, int S[])
{
    // Span value of first day is always 1
    S[0] = 1;
 
    // Calculate span value of remaining days
    // by linearly checking previous days
    for (int i = 1; i < n; i++) {
        S[i] = 1; // Initialize span value
 
        // Traverse left while the next element
        // on left is smaller than price[i]
        for (int j = i - 1;
             (j >= 0) && (price[i] >= price[j]); j--)
            S[i]++;
    }
}
 
// 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 code
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;
}
 
// This is code is contributed by rathbhupendra


C




// C program for brute force method to calculate stock span
// values
#include <stdio.h>
 
// Fills array S[] with span values
void calculateSpan(int price[], int n, int S[])
{
    // Span value of first day is always 1
    S[0] = 1;
 
    // Calculate span value of remaining days by linearly
    // checking previous days
    for (int i = 1; i < n; i++) {
        S[i] = 1; // Initialize span value
 
        // Traverse left while the next element on left is
        // smaller than price[i]
        for (int j = i - 1;
             (j >= 0) && (price[i] >= price[j]); j--)
            S[i]++;
    }
}
 
// A utility function to print elements of array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", 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;
}


Java




// Java implementation for brute force method to calculate
// stock span values
 
import java.util.Arrays;
 
class GFG {
    // method to calculate stock span values
    static void calculateSpan(int price[], int n, int S[])
    {
        // Span value of first day is always 1
        S[0] = 1;
 
        // Calculate span value of remaining days by
        // linearly checking previous days
        for (int i = 1; i < n; i++) {
            S[i] = 1; // Initialize span value
 
            // Traverse left while the next element on left
            // is smaller than price[i]
            for (int j = i - 1;
                 (j >= 0) && (price[i] >= price[j]); j--)
                S[i]++;
        }
    }
 
    // A utility function to print elements of array
    static void printArray(int arr[])
    {
        System.out.print(Arrays.toString(arr));
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int price[] = { 10, 4, 5, 90, 120, 80 };
        int n = price.length;
        int S[] = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program for brute force method to calculate stock span values
 
# Fills list S[] with span values
 
 
def calculateSpan(price, n, S):
 
    # Span value of first day is always 1
    S[0] = 1
 
    # Calculate span value of remaining days by linearly
    # checking previous days
    for i in range(1, n, 1):
        S[i] = 1   # Initialize span value
 
        # Traverse left while the next element on left is
        # smaller than price[i]
        j = i - 1
        while (j >= 0) and (price[i] >= price[j]):
            S[i] += 1
            j -= 1
 
# A utility function to print elements of array
 
 
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i], end=" ")
 
 
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
n = len(price)
S = [None] * n
 
# Fill the span values in list S[]
calculateSpan(price, n, S)
 
# print the calculated span values
printArray(S, n)
 
 
# This code is contributed by Sunny Karira


C#




// C# implementation for brute force method
// to calculate stock span values
using System;
 
class GFG {
 
    // method to calculate stock span values
    static void calculateSpan(int[] price, int n, int[] S)
    {
 
        // Span value of first day is always 1
        S[0] = 1;
 
        // Calculate span value of remaining
        // days by linearly checking previous
        // days
        for (int i = 1; i < n; i++) {
            S[i] = 1; // Initialize span value
 
            // Traverse left while the next
            // element on left is smaller
            // than price[i]
            for (int j = i - 1;
                 (j >= 0) && (price[i] >= price[j]); j--)
                S[i]++;
        }
    }
 
    // A utility function to print elements
    // of array
    static void printArray(int[] arr)
    {
        string result = string.Join(" ", arr);
        Console.WriteLine(result);
    }
 
    // Driver code
    public static void Main()
    {
        int[] price = { 10, 4, 5, 90, 120, 80 };
        int n = price.Length;
        int[] S = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S);
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
    // Javascript implementation for brute force method
    // to calculate stock span values
     
    // method to calculate stock span values
    function calculateSpan(price, n, S)
    {
  
        // Span value of first day is always 1
        S[0] = 1;
  
        // Calculate span value of remaining
        // days by linearly checking previous
        // days
        for (let i = 1; i < n; i++) {
            S[i] = 1; // Initialize span value
  
            // Traverse left while the next
            // element on left is smaller
            // than price[i]
            for (let j = i - 1; (j >= 0) && (price[i] >= price[j]); j--)
                S[i]++;
        }
    }
  
    // A utility function to print elements
    // of array
    function printArray(arr)
    {
        let result = arr.join(" ");
        document.write(result);
    }
     
    let price = [ 10, 4, 5, 90, 120, 80 ];
    let n = price.length;
    let S = new Array(n);
    S.fill(0);
 
    // Fill the span values in array S[]
    calculateSpan(price, n, S);
 
    // print the calculated span values
    printArray(S);
 
</script>


PHP




<?php
// PHP program for brute force method
// to calculate stock span values
 
// Fills array S[] with span values
function calculateSpan($price, $n, $S)
{
     
    // Span value of first
    // day is always 1
    $S[0] = 1;
     
    // Calculate span value of
    // remaining days by linearly
    // checking previous days
    for ($i = 1; $i < $n; $i++)
    {
         
        // Initialize span value
        $S[$i] = 1;
     
        // Traverse left while the next
        // element on left is smaller
        // than price[i]
        for ($j = $i - 1; ($j >= 0) &&
            ($price[$i] >= $price[$j]); $j--)
            $S[$i]++;
    }
     
        // print the calculated
        // span values
        for ($i = 0; $i < $n; $i++)
        echo $S[$i] . " ";;
     
         
}
 
    // Driver Code
    $price = array(10, 4, 5, 90, 120, 80);
    $n = count($price);
    $S = array($n);
 
    // Fill the span values in array S[]
    calculateSpan($price, $n, $S);
 
// This code is contributed by Sam007
?>


Output

1 1 2 4 5 1 

Time Complexity: O(N2)
Auxiliary Space: O(N)

The stock span problem using stack:

To solve the problem follow the below idea:

We see that S[i] on the day i can be easily computed if we know the closest day preceding i, such that the price is greater than on that day than the price on the day i. If such a day exists, let’s call it h(i), otherwise, we define h(i) = -1
The span is now computed as S[i] = i – h(i). See the following diagram
 

To implement this logic, we use a stack as an abstract data type to store the days i, h(i), h(h(i)), and so on. When we go from day i-1 to i, we pop the days when the price of the stock was less than or equal to price[i] and then push the value of day i back into the stack.

Follow the below steps to solve the problem:

  • Create a stack of type int and push 0 in it
  • Set the answer of day 1 as 1 and run a for loop to traverse the days
  • While the stack is not empty and the price of st.top is less than or equal to the price of the current day, pop out the top value
  • Set the answer of the current day as i+1 if the stack is empty else equal to i – st.top
  • Push the current day into the stack
  • Print the answer using the answer array

Below is the implementation of the above approach: 

C++




// C++ linear time solution for stock span problem
#include <bits/stdc++.h>
using namespace std;
 
// A stack based efficient method to calculate
// stock span values
void calculateSpan(int price[], int n, int S[])
{
    // Create a stack and push index of first
    // element to it
    stack<int> st;
    st.push(0);
 
    // Span value of first element is always 1
    S[0] = 1;
 
    // Calculate span values for rest of the elements
    for (int i = 1; i < n; i++) {
        // Pop elements from stack while stack is not
        // empty and top of stack is smaller than
        // price[i]
        while (!st.empty() && price[st.top()] <= price[i])
            st.pop();
 
        // If stack becomes empty, then price[i] is
        // greater than all elements on left of it,
        // i.e., price[0], price[1], ..price[i-1].  Else
        // price[i] is greater than elements after
        // top of stack
        S[i] = (st.empty()) ? (i + 1) : (i - st.top());
 
        // Push this element to stack
        st.push(i);
    }
}
 
// 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 code
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;
}


Java




// Java linear time solution for stock span problem
 
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
 
public class GFG {
    // A stack based efficient method to calculate
    // stock span values
    static void calculateSpan(int price[], int n, int S[])
    {
        // Create a stack and push index of first element
        // to it
        Deque<Integer> st = new ArrayDeque<Integer>();
        // Stack<Integer> st = new Stack<>();
        st.push(0);
 
        // Span value of first element is always 1
        S[0] = 1;
 
        // Calculate span values for rest of the elements
        for (int i = 1; i < n; i++) {
 
            // Pop elements from stack while stack is not
            // empty and top of stack is smaller than
            // price[i]
            while (!st.isEmpty()
                   && price[st.peek()] <= price[i])
                st.pop();
 
            // If stack becomes empty, then price[i] is
            // greater than all elements on left of it,
            // i.e., price[0], price[1], ..price[i-1]. Else
            // price[i] is greater than elements after top
            // of stack
            S[i] = (st.isEmpty()) ? (i + 1)
                                  : (i - st.peek());
 
            // Push this element to stack
            st.push(i);
        }
    }
 
    // A utility function to print elements of array
    static void printArray(int arr[])
    {
        System.out.print(Arrays.toString(arr));
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int price[] = { 10, 4, 5, 90, 120, 80 };
        int n = price.length;
        int S[] = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python linear time solution for stock span problem
 
# A stack based efficient method to calculate s
 
 
def calculateSpan(price, S):
 
    n = len(price)
    # Create a stack and push index of first element to it
    st = []
    st.append(0)
 
    # Span value of first element is always 1
    S[0] = 1
 
    # Calculate span values for rest of the elements
    for i in range(1, n):
 
        # Pop elements from stack while stack is not
        # empty and top of stack is smaller than price[i]
        while(len(st) > 0 and price[st[-1]] <= price[i]):
            st.pop()
 
        # If stack becomes empty, then price[i] is greater
        # than all elements on left of it, i.e. price[0],
        # price[1], ..price[i-1]. Else the price[i] is
        # greater than elements after top of stack
        S[i] = i + 1 if len(st) == 0 else (i - st[-1])
 
        # Push this element to stack
        st.append(i)
 
 
# A utility function to print elements of array
def printArray(arr, n):
    for i in range(0, n):
        print(arr[i], end=" ")
 
 
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price)+1)]
 
# Fill the span values in array S[]
calculateSpan(price, S)
 
# Print the calculated span values
printArray(S, len(price))
 
# This code is contributed by Nikhil Kumar Singh (nickzuck_007)


C#




// C# linear time solution for
// stock span problem
using System;
using System.Collections;
 
class GFG {
    // a linear time solution for
    // stock span problem A stack
    // based efficient method to calculate
    // stock span values
    static void calculateSpan(int[] price, int n, int[] S)
    {
        // Create a stack and Push
        // index of first element to it
        Stack st = new Stack();
        st.Push(0);
 
        // Span value of first
        // element is always 1
        S[0] = 1;
 
        // Calculate span values
        // for rest of the elements
        for (int i = 1; i < n; i++) {
 
            // Pop elements from stack
            // while stack is not empty
            // and top of stack is smaller
            // than price[i]
            while (st.Count > 0
                   && price[(int)st.Peek()] <= price[i])
                st.Pop();
 
            // If stack becomes empty, then price[i] is
            // greater than all elements on left of it,
            // i.e., price[0], price[1], ..price[i-1]. Else
            // price[i] is greater than elements after top
            // of stack
            S[i] = (st.Count == 0) ? (i + 1)
                                   : (i - (int)st.Peek());
 
            // Push this element to stack
            st.Push(i);
        }
    }
 
    // A utility function to print elements of array
    static void printArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver method
    public static void Main(String[] args)
    {
        int[] price = { 10, 4, 5, 90, 120, 80 };
        int n = price.Length;
        int[] S = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S);
    }
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
// javascript linear time solution for stock span problem
 
    // A stack based efficient method to calculate
    // stock span values
    function calculateSpan(price , n , S)
    {
     
        // Create a stack and push index of first element
        // to it
        var st = [];
        st.push(0);
 
        // Span value of first element is always 1
        S[0] = 1;
 
        // Calculate span values for rest of the elements
        for (var i = 1; i < n; i++) {
 
            // Pop elements from stack while stack is not
            // empty and top of stack is smaller than
            // price[i]
            while (st.length!==0 && price[st[st.length - 1]] <= price[i])
                st.pop();
 
            // If stack becomes empty, then price[i] is
            // greater than all elements on left of it, i.e.,
            // price[0], price[1], ..price[i-1]. Else price[i]
            // is greater than elements after top of stack
            S[i] = (st.length===0) ? (i + 1) : (i - st[st.length - 1]);
 
            // Push this element to stack
            st.push(i);
        }
    }
 
    // A utility function to print elements of array
    function printArray(arr) {
        document.write(arr);
    }
 
    // Driver method
     
        var price = [ 10, 4, 5, 90, 120, 80 ];
        var n = price.length;
        var S = Array(n).fill(0);
 
        // Fill the span values in array S
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S);
 
// This code contributed by Rajput-Ji
</script>


Output

1 1 2 4 5 1 

Time Complexity: O(N). It seems more than O(N) at first look. If we take a closer look, we can observe that every element of the array is added and removed from the stack at most once.
Auxiliary Space: O(N) in the worst case when all elements are sorted in decreasing order.

The stock span problem using dynamic programming:

To solve the problem follow the below idea:

Since the same subproblems are called again, this problem has the Overlapping Subproblems property. S0, the recomputations of the same subproblems can be avoided by constructing a temporary array to store already calculated answers

  • Store the answer for every index in an array and calculate the value of the next index using previous values 
  • i.e check the answer for previous element and if the value of the current element is greater than the previous element 
  • Add the answer to the previous index into current answer and then check the value of (previous index – answer of previous index) 
  • Check this condition repeatedly

Below is the implementation of the above approach:

C++




// C++ program for a linear time solution for stock
// span problem without using stack
#include <bits/stdc++.h>
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 code
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;
}


Java




// Java program for a linear time
// solution for stock span problem
// without using stack
 
import java.io.*;
 
class GFG {
 
    // An efficient method to calculate
    // stock span values implementing the
    // same idea without using stack
    static 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
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int price[] = { 10, 4, 5, 90, 120, 80 };
        int n = price.length;
        int S[] = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Python3




# Python3 program for a linear time
# solution for stock span problem
# without using stack
 
# An efficient method to calculate
# stock span values implementing
# the same idea without using stack
 
 
def calculateSpan(A, n, ans):
 
    # Span value of first element
    # is always 1
    ans[0] = 1
 
    # Calculate span values for rest
    # of the elements
    for i in range(1, n):
        counter = 1
 
        while ((i - counter) >= 0 and
               A[i] >= A[i - counter]):
            counter += ans[i - counter]
        ans[i] = counter
 
# A utility function to print elements
# of array
 
 
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i], end=' ')
    print()
 
 
# Driver code
price = [10, 4, 5, 90, 120, 80]
n = len(price)
S = [0] * (n)
 
# Fill the span values in array S[]
calculateSpan(price, n, S)
 
# Print the calculated span values
printArray(S, n)
 
# This code is contributed by Prateek Gupta


C#




// C# program for a linear time
// solution for stock span problem
// without using stack
using System;
public class GFG {
 
    // An efficient method to calculate
    // stock span values implementing the
    // same idea without using stack
    static 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
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] price = { 10, 4, 5, 90, 120, 80 };
        int n = price.Length;
        int[] S = new int[n];
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S, n);
    }
}
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
        // JavaScript program for the above approach;
 
        // An efficient method to calculate stock span values
        // implementing the same idea without using stack
        function calculateSpan(A, n, ans)
        {
         
            // Span value of first element is always 1
            ans[0] = 1;
 
            // Calculate span values for rest of the elements
            for (let i = 1; i < n; i++) {
                let 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
        function printArray(arr, n) {
            for (let i = 0; i < n; i++)
                document.write(arr[i] + " ");
        }
 
        // Driver program to test above function
        let price = [10, 4, 5, 90, 120, 80];
        let n = price.length;
        let S = new Array(n);
 
        // Fill the span values in array S[]
        calculateSpan(price, n, S);
 
        // print the calculated span values
        printArray(S, n);
         
   // This code is contributed by Potta Lokesh
    </script>


Output

1 1 2 4 5 1 

Time Complexity: O(N)
Auxiliary Space: O(N)

The stock span problem using two stacks:

Follow the below steps to solve the problem:

  • In this approach, I have used the data structure stack to implement this task.
  • Here, two stacks are used. One stack stores the actual stock prices whereas, the other stack is a temporary stack.
  • The stock span problem is solved using only the Push and Pop functions of the Stack.
  • Just to take input values, I have taken array ‘price’ and to store output, used array ‘span’.

Below is the implementation of the above approach:

C++




// C++ program for brute force method
// to calculate stock span values
#include <bits/stdc++.h>
using namespace std;
 
vector<int> calculateSpan(int arr[], int n)
{
    // Your code here
    stack<int> s;
    vector<int> ans;
    for (int i = 0; i < n; i++) {
        while (!s.empty() and arr[s.top()] <= arr[i])
            s.pop();
 
        if (s.empty())
            ans.push_back(i + 1);
        else {
            int top = s.top();
            ans.push_back(i - top);
        }
        s.push(i);
    }
 
    return ans;
}
 
// A utility function to print elements of array
void printArray(vector<int> arr)
{
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int price[] = { 10, 4, 5, 90, 120, 80 };
    int n = sizeof(price) / sizeof(price[0]);
    int S[n];
 
      // Function call
    vector<int> arr = calculateSpan(price, n);
    printArray(arr);
 
    return 0;
}
 
// This is code is contributed by Arpit Jain


C




// C program for the above approach
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 6
 
// change size of  stack from here
// change this char to int if
// you want to create stack of
// int. rest all program will work fine
typedef int stackentry;
 
typedef struct stack {
    stackentry entry[SIZE];
    int top;
} STACK;
 
// stack is initialized by setting top pointer = -1.
void initialiseStack(STACK* s) { s->top = -1; }
 
// to check if stack is full.
int IsStackfull(STACK s)
{
    if (s.top == SIZE - 1) {
        return (1);
    }
    return (0);
}
 
// to check if stack is empty.
int IsStackempty(STACK s)
{
    if (s.top == -1) {
        return (1);
    }
    else {
        return (0);
    }
}
 
// to push elements into the stack.
void push(stackentry d, STACK* s)
{
    if (!IsStackfull(*s)) {
 
        s->entry[(s->top) + 1] = d;
        s->top = s->top + 1;
    }
}
 
// to pop element from stack.
stackentry pop(STACK* s)
{
    stackentry ans;
    if (!IsStackempty(*s)) {
        ans = s->entry[s->top];
        s->top = s->top - 1;
    }
    else {
 
        // '\0'  will be returned if
        // stack is empty and of
        // char type.
        if (sizeof(stackentry) == 1)
            ans = '\0';
        else
            // INT_MIN  will be returned
            // if stack is empty
            // and of int type.
            ans = INT_MIN;
    }
    return (ans);
}
 
// The code for implementing stock
// span problem is written
// here in main function.
int main()
{
    // Just to store prices on 7 adjacent days
    int price[6] = { 10, 4, 5, 90, 120, 80 };
 
    // in span array , span of each day will be stored.
    int span[6] = { 0 };
    int i;
 
    // stack 's' will store stock values of each
    // day. stack 'temp' is temporary stack
    STACK s, temp;
 
    // setting top pointer to -1.
    initialiseStack(&s);
    initialiseStack(&temp);
 
    // count basically signifies span of
    // particular day.
    int count = 1;
 
    // since first day span is 1 only.
    span[0] = 1;
    push(price[0], &s);
 
    // calculate span of remaining days.
    for (i = 1; i < 6; i++) {
 
        // count will be span of that particular day.
        count = 1;
 
        // if current day stock is larger than previous day
        // span, then it will be popped out into temp stack.
        // popping will be carried out till span gets over
        // and count will be incremented .
 
        while (!IsStackempty(s)
               && s.entry[s.top] <= price[i]) {
            push(pop(&s), &temp);
            count++;
        }
 
        // now, one by one all stocks from temp will be
        // popped and pushed back to s.
        while (!IsStackempty(temp)) {
            push(pop(&temp), &s);
        }
 
        // pushing current stock
        push(price[i], &s);
 
        // appending span of that particular
        // day into output array.
        span[i] = count;
    }
 
    // printing the output.
    for (i = 0; i < 6; i++)
        printf("%d ", span[i]);
}


Java




// Java program for brute force method
// to calculate stock span values
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
 
class GFG {
 
    static ArrayList<Integer> calculateSpan(int arr[],
                                            int n)
    {
        // Your code here
        Deque<Integer> s = new ArrayDeque<Integer>();
        ArrayList<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            while (!s.isEmpty() && arr[s.peek()] <= arr[i])
                s.pop();
 
            if (s.isEmpty())
                ans.add(i + 1);
            else {
                int top = s.peek();
                ans.add(i - top);
            }
            s.push(i);
        }
 
        return ans;
    }
 
    // A utility function to print elements of array
    static void printArray(ArrayList<Integer> arr)
    {
        for (int i = 0; i < arr.size(); i++)
            System.out.print(arr.get(i) + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        int price[] = { 10, 4, 5, 90, 120, 80 };
        int n = price.length;
 
        ArrayList<Integer> arr = calculateSpan(price, n);
        printArray(arr);
    }
}
 
// This is code is contributed by Lovely Jain


Python3




# Python3 program for a linear time
# solution for stock span problem
# using stack
 
 
def calculateSpan(a, n):
    s = []
    ans = []
    for i in range(0, n):
 
        while(s != [] and a[s[-1]] <= a[i]):
            s.pop()
 
        if(s == []):
            ans.append(i+1)
 
        else:
            top = s[-1]
            ans.append(i - top)
 
        s.append(i)
 
    return ans
 
# A utility function to print elements
# of array
 
 
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i], end=' ')
    print()
 
 
# Driver code
price = [10, 4, 5, 90, 120, 80]
n = len(price)
ans = calculateSpan(price, n)
 
# Print the calculated span values
printArray(ans, n)
 
# This code is contributed by Arpit Jain


C#




// C# program for brute force method
// to calculate stock span values
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
    public static List<int> calculateSpan(int[] arr, int n)
    {
        // Your code here
        Stack s = new Stack();
        List<int> ans = new List<int>();
        for (int i = 0; i < n; i++) {
            while (s.Count != 0
                   && arr[(int)s.Peek()] <= arr[i])
                s.Pop();
 
            if (s.Count == 0)
                ans.Add(i + 1);
            else {
                int top = (int)s.Peek();
                ans.Add(i - top);
            }
            s.Push(i);
        }
 
        return ans;
    }
 
    // A utility function to print elements of array
    static void printArray(List<int> arr)
    {
        for (int i = 0; i < arr.Count; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] price = { 10, 4, 5, 90, 120, 80 };
        int n = price.Length;
 
        List<int> arr = calculateSpan(price, n);
        printArray(arr);
    }
}
 
// This code is contributed by karandeep1234


Javascript




// javascript program for brute force method
// to calculate stock span values
 
function calculateSpan(arr, n)
    {
       // Your code here
        let s =[];
        let ans=[];
        for(let i=0;i<n;i++)
        {
            while(s.length!=0 && arr[s[s.length-1]] <= arr[i])
                        s.pop();
                     
            if(s.length==0)
                ans.push(i+1);
            else
            {
                let top = s[s.length-1];
                ans.push(i-top);
            }
            s.push(i);
        }
     
        return ans;
    }
     
 
// Driver code
 
    let price = [ 10, 4, 5, 90, 120, 80 ];
    let n = price.length;
 
     
    let arr = calculateSpan(price, n);
    document.write(arr);


Output

1 1 2 4 5 1 

Time Complexity: O(N), where N is the size of the array. 
Auxiliary Space: O(N), where N is the size of the array. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads