Friday, August 26, 2016

The Stock Span Problem Solution in Java

The Stock Span Problem

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 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}

Solution:

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

Code:

import java.util.Stack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class TheStockSpanProblem {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int price[] = {10, 4, 5, 90, 120, 80};
stockSpanProblem(price);

}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static int[] stockSpanProblem(int[] arr)
{
Stack<Integer> s = new Stack();
Stack<Integer> s2 = new Stack();
int[] returned_arr = new int[arr.length];
int temp;
int count;
for(int i = 0;i < arr.length; i++)
{
 count = 1;
//to push elements inside it until larger element comes
if (s.empty())

s.push(arr[i]);

if (s.peek() > arr[i])
{
 s.push(arr[i]);
}
else
{
 while (!s.empty() && s.peek() < arr[i])
 {
temp = s.pop();
s2.push(temp);
count ++;
 }
s.push(arr[i]);//push this element
while (!s2.empty())
{
 s.push(s2.pop());
}//so s2 empty at last
}
returned_arr[i] = count;
System.out.println(returned_arr[i]);
  }
   return returned_arr;
}
}

Output:


1 1 2 4 5 1

But this solution is inefficient.Can be a better solution than this.

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 array is added and removed from 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.

No comments: