Merge transactions in bank sheets in the order of their occurrence such that their sum remains positive

  
import java.util.*;
  

class Node {
  
    int val;
    Node next;
  
    
    Node(int val)
    {
        this.val = val;
        this.next = null;
    }
}
  
class GFG {
  
    
    public static void mergeSheets(
        Node lists[])
    {
        
        PriorityQueue pq
  
            = new PriorityQueue(
                new Comparator() {
  
                    
                    
                    public int compare(Node a, Node b)
                    {
                        return b.val – a.val;
                    }
  
                });
  
        
        Node p, head = new Node(0);
        p = head;
  
        
        
        for (int i = 0;
             i < lists.length; i++) {                             if (lists[i] != null) {                                                      pq.add(lists[i]);             }         }                     while (!pq.isEmpty()) {             p.next = pq.poll();             p = p.next;                if (p.next != null)                 pq.add(p.next);         }            p = head.next;                     while (p.next != null) {             System.out.print(p.val + " ");             p = p.next;         }            System.out.print(p.val);     }             public static void main(String[] args)     {         int N = 2;            Node arr[] = new Node[N];            arr[0] = new Node(100);         arr[0].next = new Node(400);         arr[0].next.next = new Node(-1000);         arr[0].next.next.next = new Node(-500);            arr[1] = new Node(-300);         arr[1].next = new Node(2000);         arr[1].next.next = new Node(-500);                     mergeSheets(arr);     } }