-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgfgStockSpan.java
More file actions
31 lines (25 loc) · 796 Bytes
/
gfgStockSpan.java
File metadata and controls
31 lines (25 loc) · 796 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
import java.util.*;
public class gfgStockSpan {
public static void main(String args[]) {
int arr[] = {100, 80, 60, 70, 60, 75, 85};
ArrayList<Integer> ans = calculateSpan(arr);
System.out.println(ans);
}
public static ArrayList<Integer> calculateSpan(int[] arr) {
Stack<Integer> stack = new Stack<>();
ArrayList<Integer> ans = new ArrayList<>();
for(int i=0; i<arr.length; i++){
while(!stack.isEmpty() && arr[stack.peek()] <= arr[i]){
stack.pop();
}
if (stack.isEmpty()) {
ans.add(i - (-1));
}
else{
ans.add(i - stack.peek());
}
stack.push(i);
}
return ans;
}
}