Scoped Transaction Balances
At Razorpay, managing financial transactions accurately is paramount. In complex financial systems, transactions often occur within nested contexts or 'scopes', where a set of operations might contribute to an intermediate balance before being consolidated into a parent account. For example, a batch payment system might group multiple sub-transactions, or a refund process might temporarily isolate funds. This problem challenges you to process a series of financial operations that include starting and ending such nested scopes, ultimately calculating the final consolidated balance.
Your task is to implement a function calculateFinalBalance that processes a list of financial operations and returns the final consolidated balance. The operations can modify the current active balance or manage nested scopes.
Handle the following operations:
DEPOSIT <amount>: Adds <amount> to the current active balance.WITHDRAW <amount>: Subtracts <amount> from the current active balance.BEGIN_SCOPE: Initiates a new nested transaction scope. The current active balance is pushed onto a stack, and the new scope starts with an active balance of 0.END_SCOPE: Concludes the current nested transaction scope. The accumulated balance of the just-finished scope is added to the parent scope's balance (which was previously pushed onto the stack). The parent scope's balance then becomes the new current active balance.The initial active balance is 0.
operations: string[]
number
DEPOSIT and WITHDRAW will always be positive integers.END_SCOPE will always be called only when there is a corresponding BEGIN_SCOPE (i.e., the input will always represent a valid nesting structure).Examples
Example 1
Input:
operations = ["DEPOSIT 100", "WITHDRAW 30", "DEPOSIT 50"]
Output:
120
Note:
Initial balance: 0
Example 2
Input:
operations = ["DEPOSIT 100", "BEGIN_SCOPE", "DEPOSIT 50", "END_SCOPE", "WITHDRAW 20"]
Output:
130
Note:
Initial balance: 0
Example 3
Input:
operations = ["DEPOSIT 10", "BEGIN_SCOPE", "DEPOSIT 5", "BEGIN_SCOPE", "DEPOSIT 2", "END_SCOPE", "END_SCOPE", "DEPOSIT 1"]
Output:
18
Note:
Initial balance: 0
Constraints
1 <= operations.length <= 10^51 <= amount <= 10^9 for DEPOSIT and WITHDRAW operations.number type, which handles up to 2^53 - 1 precisely).Loading editor...