The balance sheet must satisfy
Let be the sum of undamaged asset amounts, and the sum of undamaged liability and equity amounts. Let and count damaged accounts on the asset side and on the other side, respectively.
If the computed amount is negative, restoration is impossible. Otherwise, print every undamaged account in input order, followed by the consolidated OTHER account with that type and amount. Print it even if the amount is zero.
Each input amount is at most , and there are at most accounts, so the absolute value of every sum and recovered amount is at most . Use a signed 64-bit integer.
Reading and printing the accounts takes time and space.