![]() |
VOOZH | about |
Given an array arr[][] consisting of N lists representing N transactions, the task is to merge the given lists of transactions in the order of their occurrences, such that at any point of time, the sum of already performed transactions is non-negative. If found to negative, then print "-1". Otherwise, print the merged list of transactions.
Examples:
Input: arr[][] = {{100 ? 400 ? -1000 ? -500}, {-300 ? 2000 ? -500}}
Output: 100 ? 400 ? -300 ? 2000 ? -500 ? -1000 ? -500
Explanation: The sum at every instant of the above list of transactions is given by {100, 500, 200, 2200, 1700, 700, 200}, which has no negative values.Input: arr[][] = [[100 ? 400]]
Output: 100 400
Approach: The given problem can be visualized as a variation of merge K-sorted linked lists with criteria that the sum of the merged list of transactions at any instant should be non-negative.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:-
100 400 -300 2000 -500 -1000 -500
Time Complexity: O(N * log K)
Auxiliary Space: O(K)