I/p: [10,6,8,5,11,9]
O/p: [3,1,2,1,1,0]
https://leetcode.com/problems/number-of-visible-people-in-a-queue/
package pep.Day26;
import java.util.Stack;
public class LeetCode_1944_Number_of_Visible_People_in_Queue {
public static void main(String[] args) {
int[] arr = {10, 6, 8, 5, 11, 9};
for (int x : canSeePersonsCount(arr)) {
System.out.print(x + "\t");
}
}
public static int[] canSeePersonsCount(int[] heights) {
int n = heights.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
int count = 0;
// jab tak stack ki peek pr element chota hai, pop kr do
// reason: koi bhi banda, mere current height wale bande,
// se choti height wale ko nhi dekh skta, woh shadow me chip jaega
while (!stack.isEmpty() && stack.peek() <= heights[i]) {
count++;
stack.pop();
}
// agr stack.peek pr bada element hai to, count increase kr do
if (!stack.isEmpty() && stack.peek() > heights[i])
count++;
ans[i] = count;
stack.push(heights[i]);
}
return ans;
}
}
No comments:
Post a Comment