Skip to content

Commit 76c45c1

Browse files
feat: add StockSpanProblem algorithm (#7312)
* feat: add StockSpanProblem algorithm * feat: add OptimalBinarySearchTree algorithm
1 parent be02240 commit 76c45c1

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.thealgorithms.stacks;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* Calculates the stock span for each day in a series of stock prices.
7+
*
8+
* <p>The span of a price on a given day is the number of consecutive days ending on that day
9+
* for which the price was less than or equal to the current day's price.
10+
*
11+
* <p>Idea: keep a stack of indices whose prices are strictly greater than the current price.
12+
* While processing each day, pop smaller or equal prices because they are part of the current
13+
* span. After popping, the nearest greater price left on the stack tells us where the span stops.
14+
*
15+
* <p>Time complexity is O(n) because each index is pushed onto the stack once and popped at most
16+
* once, so the total number of stack operations grows linearly with the number of prices. This
17+
* makes the stack approach efficient because it avoids rechecking earlier days repeatedly, unlike
18+
* a naive nested-loop solution that can take O(n^2) time.
19+
*
20+
* <p>Example: for prices [100, 80, 60, 70, 60, 75, 85], the spans are
21+
* [1, 1, 1, 2, 1, 4, 6].
22+
*/
23+
public final class StockSpanProblem {
24+
private StockSpanProblem() {
25+
}
26+
27+
/**
28+
* Calculates the stock span for each price in the input array.
29+
*
30+
* @param prices the stock prices
31+
* @return the span for each day
32+
* @throws IllegalArgumentException if the input array is null
33+
*/
34+
public static int[] calculateSpan(int[] prices) {
35+
if (prices == null) {
36+
throw new IllegalArgumentException("Input prices cannot be null");
37+
}
38+
39+
int[] spans = new int[prices.length];
40+
Stack<Integer> stack = new Stack<>();
41+
42+
// Small example:
43+
// prices = [100, 80, 60, 70]
44+
// spans = [ 1, 1, 1, 2]
45+
// When we process 70, we pop 60 because 60 <= 70, so the span becomes 2.
46+
//
47+
// The stack stores indices of days with prices greater than the current day's price.
48+
for (int index = 0; index < prices.length; index++) {
49+
// Remove all previous days whose prices are less than or equal to the current price.
50+
while (!stack.isEmpty() && prices[stack.peek()] <= prices[index]) {
51+
stack.pop();
52+
}
53+
54+
// If the stack is empty, there is no earlier day with a greater price,
55+
// so the count will be from day 0 to this day (index + 1).
56+
//
57+
// Otherwise, the span is the number of days between
58+
// the nearest earlier day with a greater price and the current day.
59+
spans[index] = stack.isEmpty() ? index + 1 : index - stack.peek();
60+
61+
// Store the current index as a candidate for future span calculations.
62+
stack.push(index);
63+
}
64+
65+
return spans;
66+
}
67+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.stacks;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.stream.Stream;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.MethodSource;
10+
11+
class StockSpanProblemTest {
12+
13+
@ParameterizedTest
14+
@MethodSource("validTestCases")
15+
void testCalculateSpan(int[] prices, int[] expectedSpans) {
16+
assertArrayEquals(expectedSpans, StockSpanProblem.calculateSpan(prices));
17+
}
18+
19+
private static Stream<Arguments> validTestCases() {
20+
return Stream.of(Arguments.of(new int[] {10, 4, 5, 90, 120, 80}, new int[] {1, 1, 2, 4, 5, 1}), Arguments.of(new int[] {100, 50, 60, 70, 80, 90}, new int[] {1, 1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 1, 1, 1, 1}),
21+
Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {10, 20, 30, 40, 50}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {100, 80, 60, 70, 60, 75, 85}, new int[] {1, 1, 1, 2, 1, 4, 6}),
22+
Arguments.of(new int[] {7, 7, 7, 7}, new int[] {1, 2, 3, 4}), Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {42}, new int[] {1}));
23+
}
24+
25+
@ParameterizedTest
26+
@MethodSource("invalidTestCases")
27+
void testCalculateSpanInvalidInput(int[] prices) {
28+
assertThrows(IllegalArgumentException.class, () -> StockSpanProblem.calculateSpan(prices));
29+
}
30+
31+
private static Stream<Arguments> invalidTestCases() {
32+
return Stream.of(Arguments.of((int[]) null));
33+
}
34+
}

0 commit comments

Comments
 (0)