5
\$\begingroup\$

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}

Looking for code review, optimization, and best practices.

public final class StockSpan {

    private StockSpan() {}

    public static int[] stockSpan(int[] stock) {
        // we will use stack for indexes and not for "stock values"
        final Stack<Integer> stack = new Stack<Integer>();
        int[] span = new int[stock.length];

        for (int i = 0; i < stock.length; i++) {
            int index = 0;
            span[i] = 1;
            while (!stack.isEmpty() && stock[stack.peek()] <= stock[i]) {
                index = stack.pop();
                span[i] = i - index + span[index];
            }
            stack.push(i);
        }

        return span;
    }
}

public class StockSpanTest {

    @Test
    public void test1() {
        int price1[] = {100, 80, 60, 70, 60, 75, 85};
        int expected1[] = {1, 1, 1, 2, 1, 4, 6};
        assertTrue(Arrays.equals(expected1, StockSpan.stockSpan(price1)));  
    }


    @Test
    public void test2() {
        int price2[] = {10, 4, 5, 90, 120, 80};
        int expected2[] = {1, 1, 2, 4, 5, 1};
        assertTrue(Arrays.equals(expected2, StockSpan.stockSpan(price2)));
    }
}
\$\endgroup\$
0
3
\$\begingroup\$

The basic algorithm here looks decent.... though the use of the Stack is overkill. There is no need to keep previous members. in fact, a simple while loop, using what you have learned in previous loops, will be fine.

Consider this:

public static int[] stockSpan(int[] stock) {
    // we will use stack for indexes and not for "stock values"
    int[] span = new int[stock.length];

    for (int i = 0; i < stock.length; i++) {
        int index = i - 1;
        span[i] = 1;
        while (index >= 0 && stock[index] <= stock[i]) {
            // previous member is the same or smaller price.
            // that member, plus all of its span, are also smaller.
            span[i] += span[index];
            // we can skip the span and check if the next span is smaller too.
            index -= span[index];
        }
    }

    // System.out.printf("Input %s -> SPans %s%n",
    //        Arrays.toString(stock), Arrays.toString(span));
    return span;
}
\$\endgroup\$
0
\$\begingroup\$
  • Stock prices should be doubles, not integers.

  • Use List, not arrays. It is very old fashioned to use arrays. [EDIT: Oops... see comments.]

  • There is no need for the stack:

public static List<Integer> findSpans(List<Double> stocks) {
    if (stocks.isEmpty())
        throw new IllegalArgumentException();
    List<Integer> spans = new ArrayList<>(stocks.size());
    for (int i = 0; i < stocks.size(); i++) {
        int span = 1;
        {
            int previousSpanIndex = i - 1;
            while (previousSpanIndex >= 0 && (stocks.get(i) >= stocks.get(previousSpanIndex))) {
                span += spans.get(previousSpanIndex);
                previousSpanIndex -= spans.get(previousSpanIndex);
            }
        }
        spans.add(span);
    }
    return spans;
}
\$\endgroup\$
4
  • \$\begingroup\$ Hmmm... I am inspired to criticise this answer because, in this case, "Old Fashioned" is good. \$\endgroup\$ – rolfl Jun 27 '14 at 19:59
  • \$\begingroup\$ @rolfl What do you mean? Faster indexing or faster comparison (<=) on raw doubles? \$\endgroup\$ – toto2 Jun 27 '14 at 20:01
  • \$\begingroup\$ List is not an improvement for this code, it slows it down significanly (I would guess about 4X). \$\endgroup\$ – rolfl Jun 27 '14 at 20:02
  • 1
    \$\begingroup\$ @rolfl Not a bad prediction. I carried out some testing and I got 3X slower for List. \$\endgroup\$ – toto2 Jun 27 '14 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.