Created
July 21, 2020 15:23
-
-
Save pratik7368patil/aa17bd44d25eb5a29be5f56692e52e8d to your computer and use it in GitHub Desktop.
Stock Span Problem Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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