Open In App

The Stock Span Problem

Last Updated : 12 Jun, 2024
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
Python
# 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
Python
# 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.



Previous Article
Next Article

Similar Reads

Longest Span with same Sum in two Binary arrays
Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j &gt;= i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].The expected time complexity is ?(n). Examples: Input: arr1[] = {0, 1, 0, 0, 0, 0}; arr2[] = {1, 0, 1, 0, 0, 1}; Output: 4 The longest
15+ min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Maximum profit by buying and selling a stock at most twice | Set 2
Given an array prices[] which denotes the prices of the stocks on different days, the task is to find the maximum profit possible after buying and selling the stocks on different days using transaction where at most two transactions are allowed.Note: You cannot engage in multiple transactions at the same time (i.e., you must sell the stock before y
10 min read
C Program For Stock Buy Sell To Maximize Profit
Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store i
3 min read
GE Stock Price Analysis Using R Language
Stock analysis is a technique used by investors and traders to make purchasing and selling choices. Investors and traders strive to obtain an advantage in the markets by making educated judgments by researching and analyzing previous and current data. In this article, we will analyze the 'GE Stock Price' dataset using the R Programming Language. Th
5 min read
Python Program For Stock Buy Sell To Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in de
5 min read
Article Tags :
Practice Tags :