int[] a = new int[prices.length];
stack.push(0);
a[0] = 1;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < prices[stack.top()]) {
while (!stack.isEmpty()) {
stack.pop();
}
}
stack.push(i);
a[i] = stack.size();
}
return a;
}
int[] a = new int[prices.length];
stack.push(0);
a[0] = 1;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < prices[stack.top()]) {
while (!stack.isEmpty()) {
stack.pop();
}
}
stack.push(i);
a[i] = stack.size();
}
return a;
}
refer tot this:
public static int[] StockSpanUsingStacks(int[] prices, Stack<Integer> stack) throws Exception {
// span array stores the value of stock span for each day
int[] span = new int[prices.length];
// pushing the index of first day
stack.push(0);
// span for 1st day will always be 1
span[0] = 1;
// Iterating over the prices array
for (int i = 1; i < prices.length; i++) {
// poping days from stack when price of the i th day is greater than the price of day which is on top of stack
while (stack.size() != 0 && prices[i] > prices[stack.top()]) {
stack.pop();
}
if (stack.size() == 0) {
// then all the previous prices are smaller than the price on the ith day
span[i] = i + 1;
} else {
// the previous highest price will be on the top of the stack
span[i] = i - stack.top();
}
// pushing the index of the price array which is the number of day in stack
stack.push(i);
}
return span;
}