×

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The maximum number of days before a particular day for which the stock price on the current day is less than the given day is known as the span Si of the stock's price on that day.

The financial element includes "The Stock Span Problem." This task determines the stock span for each day's stock price. The longest stretch of days preceding a specific day when the stock price is lower than or the same as the stock price on those days is known as the gap. The span Si of the stock's price on that day is defined as the maximum number of days just before the given day for which the stock's price today is less than or equal to its price on the given day.

Problem Statement

A list of a stock's prices for N days is provided. Find the stack span for each day is the problem at hand.

The stock gap is K before the number of days before the current day that the stock price was either equal to or lower than the present price.

Example 1

N = 7, and the stock_price[] = [101 85 61 73 66 77 110]

Output:

 [1 1 1 2 1 4 7 ]

Explanation: When traversing the input given, the span for 101 will be 1, 85 will be less than 101, 61 will be less than 80, 73 will be higher than 61, and 66 will be smaller than 73. Finally, since the span is and 110 is more than all of the elements, the result will be 1 1 1 2 1 4 6.

Example 2

Input: [100, 80, 60, 70, 60, 75, 85]

Output : [1, 1, 1, 2, 1, 4, 6] 

Explanation:

There is no prior day for which the stock price was less than or equal to day 1's price of 100. The span is, therefore, 1.

There is no prior day where the price was less than or equal to day 2's price of 80 for the stock. The span is, therefore, 1.

There is no prior day where the price was less than or equal to day 3's price of 60 for the stock. The span is, therefore, 1.

The stock's price on day 4 is 70, and day 3's stock price of 60 is less than or equal to day 4's stock price (70). hence, the spread is two (as there are two consecutive days, day 3 and day 4, for which the stock price is less than or equal to 70).

The stock is priced at 60 for day 5, while day 4's stock price (70) was higher than day 5's price (60). The span is, therefore, 1.

For day 6, the stock price is 75, and the stock on day 5 (60) is less than or equal to day 6 (75). Hence, the span is 4 (as there are four consecutive days, day 3, day 4, day 5, and day 6, for which the stock price is less than or equal to 75).

For day 7, the stock price is 85, and the stock on day 6 (75) is less than or equal to the price on day 7 (85). Hence, the span is 6 (as there are six consecutive days, day 2, day 3, day 4, day 5, day 6, and day 7, for which the stock price is less than or equal to 85).

Naïve Approach

The stock span problem seeks to identify the number of days a stock has been able to remain at or above a certain price. This problem can be solved using a brute force approach, which involves looping through each day in the stock data and counting the days that the price remains at or above the given price. The brute force approach would require looping through the stock data multiple times and could become computationally expensive if the data set is large.

Main.java

import java.util.Arrays;
class Main
{
	static void spanCaluclate(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));
	}
// Main section of the program where execution begins
	public static void main(String[] s)
	{
		// stock array declaration
		int stock[] = { 10, 5, 4, 91, 89, 99 };
		// finding the length of the stock array 
		int l = stock.length;
		// creating an array to store the span values
		int arr[] = new int[l];
		// Fill the span values in array arr[]
		spanCaluclate(stock, l, arr);
		// printing the array
		System. out.println("The stock span array is ");
		printArray(arr);
	}
}

Output

The stock span array is 
[1, 1, 1, 4, 1, 6]

Approach Using Stacks

We can see that S[i] on the day i can be calculated easily if we know the day that is immediately prior beforehand. The price is higher on that day than on the day i. Let's call such a day h(i) if it exists; else, we define h(i) = -1.

S[i] = i - h is now used to calculate the span (i).

We utilize a stack as an abstract data type to store the days I h(i), h(h(i)), and so on to put this logic into practice. When moving from day i-1 today i, we push the value of day I back into the stack after popping the days when the stock price was less than or equal to price[i].

Pseudo Code

  • Make an int stack and place 0 in it.
  • Set the response on day 1 as 1, then iterate through the days using a loop.
  • Pop out the top value as long as the stack is not empty and the price of st. to p is lower than or equal to the price of the current day.
  • Set the current day's response to i+1. If the stack is full; otherwise, i - st. top
  • Place today on top of the stack.
  • Print the solution utilizing the solution array.

Note: We must also consider the possibility that all stock prices should be equal, in which case we must only determine whether the current stock price is higher than the prior one. We won't pop from the stack when the stock price is the same today as yesterday.

StockSpanProblem.java

// importing required packages
import java. util.ArrayDeque;
import java. util.Arrays;
import java. util.Deque;
// Main class declaration 
public class StockSpanProblem {
	// An effective way to calculate stock span values using stacks
	static void spanCaluclate(int price[], int n, int arr[])
	{
		// Creating  a stack and pushing the index of the array’s first element into it
		Deque<Integer> sta = new ArrayDeque<Integer>();
		sta.push(0);


		// The first element's span value is always 1.
		//Because there is no element to the right of the 1st element
		arr[0] = 1;
		// calculating the span values for the remaining elements
		
		for (int j = 1; j < n; j++) {


			// When the stack is not empty, and the top is smaller than the price, remove elements[i].
			while (!sta.isEmpty() && price[sta.peek()] <= price[j])
				sta.pop();


			// Price[i] is greater than all elements to the left of it if the stack becomes empty.
		    // Otherwise, the price[i] exceeds the components below the top of the stack.
			arr[j] = (sta.isEmpty()) ? (j + 1) : (j - sta.peek());


			// Push this element to stack
			sta.push(j);
		}
	}


	// A function for printing elements of the array
	static void printArray(int arr[])
	{
		System.out.print(Arrays.toString(arr));
	}


	// Main section of the program where execution begins
	public static void main(String[] s)
	{
		// stock array declaration
		int stock[] = { 10, 5, 4, 91, 89, 99 };
		// finding the length of the stock array 
		int l = stock.length;
		// creating an array to store the span values
		int arr[] = new int[l];




		// Fill the span values in array arr[]
		spanCaluclate(stock, l, arr);
		// printing the array
		System. out.println("The stock span array is ");
		printArray(arr);
	}
}

Output

The stock span array is
[1, 1, 1, 4, 1, 6]

Complexity Analysis

The time complexity is O(N). At first glance, it seems to be more than O(N). A deeper inspection reveals that each element of the array gets added to and removed from the stack a maximum of once.

In the worst-case scenario, when all elements are arranged in decreasing order, auxiliary space is O(N).


Related Topics

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.