Reputation: 341
In the given array, I want to count the only consecutive values to the left which are smaller or equal to the each value.
For example in the following array, first index value is 100, there is no smaller value than it so, it will be 1. For the value 70, there is 60 which is smaller than it, so the count is 2, and so on.
Note: This should be done using stack (its a stack practice problem).
My approach:
I'm trying to solve this way:
stack.peek()
is greater then add 1.stack.peek()
is smaller then loop through the stack as long as there are smaller or equal values.Problem:
Now the problem is that: Because of the stack.pop()
it will work first time correctly but for next time it will not.
Question:
My question is that, how can I loop through the stack without stack.pop()
?
Code: Here's what I'm trying:
public static int[] getStockSpan(int[] prices) {
int[] arr = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for ( int i = 0; i < prices.length; i++ ) {
if ( stack.size() == 0 ) {
arr[0] = 1;
} else {
if ( stack.peek() > prices[i] ) {
arr[i] = 1;
} else {
int count = 1;
while ( stack.size() > 0 && stack.peek() <= prices[i] ) {
count++;
stack.pop();
}
arr[i] = count;
}
}
stack.push(prices[i]);
}
return arr;
}
Upvotes: 0
Views: 2131
Reputation: 247
Import these in java :
import java.util.*;
import java.util.Stack;
Then replace your code with this :
public static int[] getStockSpan(int[] prices) {
int[] arr = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for ( int i = 0; i < prices.length; i++ ) {
if ( stack.size() == 0 ) {
arr[0] = 1;
} else {
if ( stack.peek() > prices[i] ) {
arr[i] = 1;
} else {
int count = 1,t=0;
Iterator iter=stack.iterator();
int ia[]=new int[prices.length];
while ( iter.hasNext() ) {
Integer k= (Integer)iter.next();
ia[t++]=k.intValue();
}
for(int j=t-1;j>=0;j--)
{
if(ia[j] <= prices[i])
count++;
else
break;
}
arr[i] = count;
}
}
stack.push(prices[i]);
}
return arr;
}
Upvotes: 1