Skip to content

Instantly share code, notes, and snippets.

@pratik7368patil
Created July 21, 2020 15:23
Show Gist options
  • Save pratik7368patil/aa17bd44d25eb5a29be5f56692e52e8d to your computer and use it in GitHub Desktop.
Save pratik7368patil/aa17bd44d25eb5a29be5f56692e52e8d to your computer and use it in GitHub Desktop.
Stock Span Problem Solution
import java.util.*;
class ValueWithCount {
int value;
int index;
ValueWithCount(int value, int index) {
this.value = value;
this.index = index;
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Stack<ValueWithCount> stack = new Stack<>();
int[] arr = new int[N];
for(int i=0; i<N; i++) {
arr[i] = sc.nextInt();
int count = 1;
while(stack.size() !=0 && stack.peek().value <= arr[i]) {
count += stack.pop().index;
}
stack.push(new ValueWithCount(arr[i], count));
System.out.print(count +" ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment