Skip to content

Commit 9f2bd82

Browse files
authored
Update Stock Span
1 parent 2b5ed0d commit 9f2bd82

File tree

1 file changed

+37
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 9 - Stacks

1 file changed

+37
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 9 - Stacks/Stock Span

+37
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,40 @@ Sample Input 2:
3434
Sample Output 2:
3535
1 2 3 4 1 1 2 8
3636
*/
37+
import java.util.Stack;
38+
public class Solution {
39+
40+
public static int[] stockSpan(int[] price) {
41+
//Your code goes here
42+
int[] span=new int[price.length];
43+
Stack<Integer> stack=new Stack<Integer>();
44+
span[0]=1;
45+
stack.push(0);
46+
47+
for (int i=1;i<price.length;i++)
48+
{
49+
while(!stack.isEmpty() && price[stack.peek()]<price[i])
50+
{
51+
stack.pop();
52+
}
53+
//System.out.println(stack.size());
54+
55+
if (stack.isEmpty())
56+
{
57+
span[i]=i+1;
58+
}
59+
else
60+
{
61+
//System.out.println("i = "+i);
62+
//System.out.println("top = "+stack.peek());
63+
span[i]=i-stack.peek();
64+
}
65+
stack.push(i);
66+
//System.out.println("New top: "+stack.peek());
67+
//System.out.println();
68+
}
69+
return span;
70+
71+
}
72+
73+
}

0 commit comments

Comments
 (0)