The Stock Span Problem in java

    Stocks are everywhere today. This problem deals with stock span calculation for all days. To calculate this, check the stock prices for consecutive days before the day given to you. The logic is to check the stock price on current day with the price on the given day.

This problem can be implemented in java as follows.

  • ·       First,use the builtin Stack package.
  • ·       Write a public class spanStockCalc with main() function.
  • ·       Include a function spanCalculate() with an argument sprices as integer.
  • ·       Find the length of the sprices and store it into variable ‘n’.
  • ·       Next,create a integer array with the size of n.
  • ·       A new object is created for stack.
  • ·       Using a for loop, check the two conditions. one is stackis empty or not , another one is check the stack elements with stack’s top elements.
  • ·       If these two conditions met, pop the element.
  • ·       Repeat the process.
  • ·       Finally, insert the element in stack.
  • ·       Inside the main function, assign values for array elements.
  • ·       Call the function and print the output.

Program:

import java.util.Stack;

public class spanStockCalc {

    // Function to calculate the stock span prices

    public static int[] spanCalculate(int[] sprices) {

        int n = sprices.length;

        int[] span = new int[n];

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

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

            // Calculation

            while (!stack1.isEmpty() && sprices[stack1.peek()] <= sprices[i]) {

                stack1.pop();

            }

            span[i] = (stack1.isEmpty()) ? (i + 1) : (i - stack1.peek());

            // insert the data

            stack1.push(i);

        }

        return span;

    }

    public static void main(String[] args) {

        int[] sprices = {450,30,70, 80, 90,175,120};

        int[] span = spanCalculate(sprices);

        // Final outcome

        System.out.print("Spans: ");

        for (int spans : span) {

            System.out.print(spans + " ");

        }

    }

}

Compile and run the program to get the output.

C:\raji\blog>javac spanStockCalc.java

C:\raji\blog>java spanStockCalc

Spans: 1 1 2 3 4 5 1

Note: Time complexity is O(n).

No comments:

Post a Comment