Advertisement
unknown_0711

Untitled

Jan 16th, 2023
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Solution {
  4. public int[] asteroidCollision(int[] arr) {
  5.  
  6. //Write code here
  7. Stack<Integer> s = new Stack<>();
  8. int n = arr.length;
  9. for (int i = 0; i < n; i++) {
  10. if (arr[i] > 0) s.push(arr[i]);
  11. else {
  12. while (
  13. !s.empty() && s.peek() > 0 && s.peek() < Math.abs(arr[i])
  14. ) s.pop();
  15. if (!s.empty() && s.peek() == Math.abs(arr[i])) {
  16. s.pop();
  17. continue;
  18. }
  19. if (s.empty() || s.peek() < 0) s.push(arr[i]);
  20. }
  21. }
  22.  
  23. int[] result = new int[s.size()];
  24. int k = 0;
  25. while (!s.empty()) {
  26. result[k++] = s.pop();
  27. }
  28. for (int i = 0; i < result.length / 2; i++) {
  29. int temp = result[i];
  30. result[i] = result[result.length - i - 1];
  31. result[result.length - i - 1] = temp;
  32. }
  33. return result;
  34. }
  35. }
  36.  
  37. public class Main {
  38. public static void main(String[] args) {
  39. Scanner sc = new Scanner(System.in);
  40. int n;
  41. n = sc.nextInt();
  42. int arr[] = new int[n];
  43. for (int i = 0; i < n; i++)
  44. arr[i] = sc.nextInt();
  45. Solution Obj = new Solution();
  46. int[] result = Obj.asteroidCollision(arr);
  47. for (int i = 0; i < result.length; ++i)
  48. System.out.print(result[i] + " ");
  49. System.out.println();
  50. sc.close();
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement