Skip to content

Commit 843d28e

Browse files
authored
Create Stack-Stock Span
1 parent 7a9da11 commit 843d28e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Stack-Stock Span

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Afzal has been working with an organization called 'Money Traders' for the past few years. The organization is into the money trading business. His manager assigned him a task. For a given array/list of stock's prices for N days, find the stock's span for each day.
2+
The span of the stock's price today is defined as the maximum number of consecutive days(starting from today and going backwards) for which the price of the stock was less than today's price.
3+
For example, if the price of a stock over a period of 7 days are [100, 80, 60, 70, 60, 75, 85], then the stock spans will be [1, 1, 1, 2, 1, 4, 6].
4+
Explanation:
5+
On the sixth day when the price of the stock was 75, the span came out to be 4, because the last 4 prices(including the current price of 75) were less than the current or the sixth day's price.
6+
7+
Similarly, we can deduce the remaining results.
8+
Afzal has to return an array/list of spans corresponding to each day's stock's price. Help him to achieve the task.
9+
Input Format:
10+
The first line of input contains an integer N, denoting the total number of days.
11+
12+
The second line of input contains the stock prices of each day. A single space will separate them.
13+
Output Format:
14+
The only line of output will print the span for each day's stock price. A single space will separate them.
15+
Note:
16+
You are not required to print the expected output explicitly. It has already been taken care of.
17+
Constraints:
18+
0 <= N <= 10^7
19+
1 <= X <= 10^9
20+
Where X denotes the stock's price for a day.
21+
22+
Time Limit: 1 second
23+
Sample Input 1:
24+
4
25+
10 10 10 10
26+
Sample Output 1:
27+
1 1 1 1
28+
Sample Input 2:
29+
8
30+
60 70 80 100 90 75 80 120
31+
Sample Output 2:
32+
1 2 3 4 1 1 2 8
33+
34+
********************************************Code******************************************
35+
public static int[] stockSpan(int[] price) {
36+
37+
if (price.length == 0) {
38+
return new int[]{0};
39+
}
40+
int[] span = new int[price.length];
41+
Stack<Integer> stack = new Stack<Integer>();
42+
span[0] = 1;
43+
stack.push(0);
44+
45+
for (int i = 1; i < price.length; i++) {
46+
while (!stack.isEmpty() && price[stack.peek()] < price[i]) {
47+
stack.pop();
48+
}
49+
50+
if (stack.isEmpty()) {
51+
span[i] = i + 1;
52+
} else {
53+
span[i] = i - stack.peek();
54+
}
55+
stack.push(i);
56+
}
57+
return span;
58+
}

0 commit comments

Comments
 (0)