-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstockproblem.java
More file actions
36 lines (28 loc) · 927 Bytes
/
stockproblem.java
File metadata and controls
36 lines (28 loc) · 927 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Stack;
public class StockSpanProblem {
public static int[] calculateSpan(int[] arr) {
int n = arr.length;
int[] span = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
stack.pop();
}
span[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}
return span;
}
public static void main(String[] args) {
int[] stockPrices = {100, 80, 60, 70, 60, 75, 85};
int[] span = calculateSpan(stockPrices);
System.out.println("Stock Prices: ");
for (int price : stockPrices) {
System.out.print(price + " ");
}
System.out.println("\nStock Spans: ");
for (int s : span) {
System.out.print(s + " ");
}
}
}