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 span of 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. 
For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6} 

A Simple but inefficient method 
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.
Following is the implementation of this method:

C++

#include <bits/stdc++.h>

using namespace std;

void calculateSpan(int price[], int n, int S[])

{

    S[0] = 1;

    for (int i = 1; i < n; i++)

    {

        S[i] = 1;

        for (int j = i - 1; (j >= 0) &&

                (price[i] >= price[j]); j--)

            S[i]++;

    }

}

void printArray(int arr[], int n)

{

    for (int i = 0; i < n; i++)

        cout << arr[i] << ;

}

int main()

{

    int price[] = { 10, 4, 5, 90, 120, 80 };

    int n = sizeof(price) / sizeof(price[0]);

    int S[n];

    calculateSpan(price, n, S);

    printArray(S, n);

    return 0;

}

C

#include <stdio.h>

void calculateSpan(int price[], int n, int S[])

{

    S[0] = 1;

    for (int i = 1; i < n; i++) {

        S[i] = 1;

        for (int j = i - 1; (j >= 0) && (price[i] >= price[j]); j--)

            S[i]++;

    }

}

void printArray(int arr[], int n)

{

    for (int i = 0; i < n; i++)

        printf(%d , arr[i]);

}

int main()

{

    int price[] = { 10, 4, 5, 90, 120, 80 };

    int n = sizeof(price) / sizeof(price[0]);

    int S[n];

    calculateSpan(price, n, S);

    printArray(S, n);

    return 0;

}

Java

import java.util.Arrays;

class GFG {

    static void calculateSpan(int price[], int n, int S[])

    {

        S[0] = 1;

        for (int i = 1; i < n; i++) {

            S[i] = 1;

            for (int j = i - 1; (j >= 0) && (price[i] >= price[j]); j--)

                S[i]++;

        }

    }

    static void printArray(int arr[])

    {

        System.out.print(Arrays.toString(arr));

    }

    public static void main(String[] args)

    {

        int price[] = { 10, 4, 5, 90, 120, 80 };

        int n = price.length;

        int S[] = new int[n];

        calculateSpan(price, n, S);

        printArray(S);

    }

}

Python3

def calculateSpan(price, n, S):

    S[0] = 1

    for i in range(1, n, 1):

        S[i] = 1  

        j = i - 1

        while (j>= 0) and (price[i] >= price[j]) :

                       S[i] += 1

                       j -= 1

def printArray(arr, n):

    for i in range(n):

        print(arr[i], end = )

price = [10, 4, 5, 90, 120, 80]

n = len(price)

S = [None] * n

calculateSpan(price, n, S)

printArray(S, n)

C#

using System;

class GFG {

    static void calculateSpan(int[] price,

                              int n, int[] S)

    {

        S[0] = 1;

        for (int i = 1; i < n; i++) {

            S[i] = 1;

            for (int j = i - 1; (j >= 0) && (price[i] >= price[j]); j--)

                S[i]++;

        }

    }

    static void printArray(int[] arr)

    {

        string result = string.Join( , arr);

        Console.WriteLine(result);

    }

    public static void Main()

    {

        int[] price = { 10, 4, 5, 90, 120, 80 };

        int n = price.Length;

        int[] S = new int[n];

        calculateSpan(price, n, S);

        printArray(S);

    }

}

PHP

<?php

function calculateSpan($price, $n, $S)

{

    $S[0] = 1;

    for ($i = 1; $i < $n; $i++)

    {

        $S[$i] = 1;

        for ($j = $i - 1; ($j >= 0) &&

            ($price[$i] >= $price[$j]); $j--)

            $S[$i]++;

    }

        for ($i = 0; $i < $n; $i++)

        echo $S[$i] . ;;

}

    $price = array(10, 4, 5, 90, 120, 80);

    $n = count($price);

    $S = array($n);

    calculateSpan($price, $n, $S);

?>

Javascript

<script>

    function calculateSpan(price, n, S)

    {

        S[0] = 1;

        for (let i = 1; i < n; i++) {

            S[i] = 1;

            for (let j = i - 1; (j >= 0) && (price[i] >= price[j]); j--)

                S[i]++;

        }

    }

    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);

    calculateSpan(price, n, S);

    printArray(S);

</script>

The Time Complexity of the above method is O(n^2). We can calculate stock span values in O(n) time.
 


A Linear-Time Complexity Method 
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.
Following is the implementation of this method. 

C++

#include <iostream>

#include <stack>

using namespace std;

void calculateSpan(int price[], int n, int S[])

{

    stack<int> st;

    st.push(0);

    S[0] = 1;

    for (int i = 1; i < n; i++) {

        while (!st.empty() && price[st.top()] <= price[i])

            st.pop();

        S[i] = (st.empty()) ? (i + 1) : (i - st.top());

        st.push(i);

    }

}

void printArray(int arr[], int n)

{

    for (int i = 0; i < n; i++)

        cout << arr[i] << ;

}

int main()

{

    int price[] = { 10, 4, 5, 90, 120, 80 };

    int n = sizeof(price) / sizeof(price[0]);

    int S[n];

    calculateSpan(price, n, S);

    printArray(S, n);

    return 0;

}

Java

import java.util.Stack;

import java.util.Arrays;

public class GFG {

    static void calculateSpan(int price[], int n, int S[])

    {

        Stack<Integer> st = new Stack<>();

        st.push(0);

        S[0] = 1;

        for (int i = 1; i < n; i++) {

            while (!st.empty() && price[st.peek()] <= price[i])

                st.pop();

            S[i] = (st.empty()) ? (i + 1) : (i - st.peek());

            st.push(i);

        }

    }

    static void printArray(int arr[])

    {

        System.out.print(Arrays.toString(arr));

    }

    public static void main(String[] args)

    {

        int price[] = { 10, 4, 5, 90, 120, 80 };

        int n = price.length;

        int S[] = new int[n];

        calculateSpan(price, n, S);

        printArray(S);

    }

}

Python3

def calculateSpan(price, S):

    n = len(price)

    st = []

    st.append(0)

    S[0] = 1

    for i in range(1, n):

        while( len(st) > 0 and price[st[-1]] <= price[i]):

            st.pop()

        S[i] = i + 1 if len(st) <= 0 else (i - st[-1])

        st.append(i)

def printArray(arr, n):

    for i in range(0, n):

        print (arr[i], end = )

price = [10, 4, 5, 90, 120, 80]

S = [0 for i in range(len(price)+1)]

calculateSpan(price, S)

printArray(S, len(price))

C#

using System;

using System.Collections;

class GFG {

    static void calculateSpan(int[] price, int n, int[] S)

    {

        Stack st = new Stack();

        st.Push(0);

        S[0] = 1;

        for (int i = 1; i < n; i++) {

            while (st.Count > 0 && price[(int)st.Peek()] <= price[i])

                st.Pop();

            S[i] = (st.Count == 0) ? (i + 1) : (i - (int)st.Peek());

            st.Push(i);

        }

    }

    static void printArray(int[] arr)

    {

        for (int i = 0; i < arr.Length; i++)

            Console.Write(arr[i] + );

    }

    public static void Main(String[] args)

    {

        int[] price = { 10, 4, 5, 90, 120, 80 };

        int n = price.Length;

        int[] S = new int[n];

        calculateSpan(price, n, S);

        printArray(S);

    }

}

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. So there are total 2n operations at most. Assuming that a stack operation takes O(1) time, we can say that the time complexity is O(n).
Auxiliary Space: O(n) in worst case when all elements are sorted in decreasing order.

Another approach: (without using stack)  

C++

#include <iostream>

#include <stack>

using namespace std;

void calculateSpan(int A[], int n, int ans[])

{

    ans[0] = 1;

    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;

    }

}

void printArray(int arr[], int n)

{

    for (int i = 0; i < n; i++)

        cout << arr[i] << ;

}

int main()

{

    int price[] = { 10, 4, 5, 90, 120, 80 };

    int n = sizeof(price) / sizeof(price[0]);

    int S[n];

    calculateSpan(price, n, S);

    printArray(S, n);

    return 0;

}

Java

class GFG {

    static void calculateSpan(int A[],

                              int n, int ans[])

    {

        ans[0] = 1;

        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;

        }

    }

    static void printArray(int arr[], int n)

    {

        for (int i = 0; i < n; i++)

            System.out.print(arr[i] + );

    }

    public static void main(String[] args)

    {

        int price[] = { 10, 4, 5, 90, 120, 80 };

        int n = price.length;

        int S[] = new int[n];

        calculateSpan(price, n, S);

        printArray(S, n);

    }

}

Python3

def calculateSpan(A, n, ans):

    ans[0] = 1

    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

def printArray(arr, n):

    for i in range(n):

        print(arr[i], end = )

    print()

price = [ 10, 4, 5, 90, 120, 80 ]

n = len(price)

S = [0] * (n)

calculateSpan(price, n, S)

printArray(S, n)

C#

using System;

public class GFG {

    static void calculateSpan(int[] A,

                              int n, int[] ans)

    {

        ans[0] = 1;

        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;

        }

    }

    static void printArray(int[] arr, int n)

    {

        for (int i = 0; i < n; i++)

            Console.Write(arr[i] + );

    }

    public static void Main(String[] args)

    {

        int[] price = { 10, 4, 5, 90, 120, 80 };

        int n = price.Length;

        int[] S = new int[n];

        calculateSpan(price, n, S);

        printArray(S, n);

    }

}

Javascript

<script>

       function calculateSpan(A, n, ans)

       {

           ans[0] = 1;

           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;

           }

       }

       function printArray(arr, n) {

           for (let i = 0; i < n; i++)

               document.write(arr[i] + );

       }

       let price = [10, 4, 5, 90, 120, 80];

       let n = price.length;

       let S = new Array(n);

       calculateSpan(price, n, S);

       printArray(S, n);

   </script>

A Stack Based approach :

  1. In this approach, I have used the data structure stack to implement this task.
  2. Here, two stacks are used. One stack stores the actual stock prices whereas, the other stack is a temporary stack.
  3. The stock span problem is solved using only the Push and Pop functions of Stack.
  4. 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

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

#define SIZE 7

typedef int stackentry;

typedef struct stack {

    stackentry entry[SIZE];

    int top;

} STACK;

void initialiseStack(STACK* s) { s->top = -1; }

int IsStackfull(STACK s)

{

    if (s.top == SIZE - 1) {

        return (1);

    }

    return (0);

}

int IsStackempty(STACK s)

{

    if (s.top == -1) {

        return (1);

    }

    else {

        return (0);

    }

}

void push(stackentry d, STACK* s)

{

    if (!IsStackfull(*s)) {

        s->entry[(s->top) + 1] = d;

        s->top = s->top + 1;

    }

}

stackentry pop(STACK* s)

{

    stackentry ans;

    if (!IsStackempty(*s)) {

        ans = s->entry[s->top];

        s->top = s->top - 1;

    }

    else {

        if (sizeof(stackentry) == 1)

            ans = /0;

        else

            ans = INT_MIN;

    }

    return (ans);

}

int main()

{

    int price[7] = { 100, 80, 60, 70, 60, 75, 85 };

    int span[7] = { 0 };

    int i;

    STACK s, temp;

    initialiseStack(&s);

    initialiseStack(&temp);

    int count = 1;

    span[0] = 1;

    push(price[0], &s);

    for (i = 1; i < 7; i++) {

        count = 1;

        while (!IsStackempty(s)

               && s.entry[s.top] <= price[i]) {

            push(pop(&s), &temp);

            count++;

        }

        while (!IsStackempty(temp)) {

            push(pop(&temp), &s);

        }

        push(price[i], &s);

        span[i] = count;

    }

    for (i = 0; i < 7; i++)

        printf(%d , span[i]);

}

which was the same expected output.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


Say hello

Find us at the office

Overmann- Mucha street no. 55, 74667 Papeete, French Polynesia

Give us a ring

Juanfrancisco Develder
+76 987 423 417
Mon - Fri, 8:00-17:00

Reach out