Alex is going to some stores where he will carry out some transactions. In each store, he will either pay some money, or he will receive some money. Initially, Alex has 0 amount with him. So he currently has an array 'money' containing the transaction amounts (both positive and negative) in the same order he did at stores. Can you find out the maximum amount that he will have with him after any(possibly 0) number of transactions?
Note: that at some point, the amount left with Alex can become negative. For example, in the transactions [1, -3], after the second transaction, the money left with Alex is -2.
Example: Let the transaction amounts be [1, -2, 5]. Here we can see that the amount left after the first transaction is 1 after the second is -1 and after the third is 4. So the maximum value is 4.
The first line contains ‘T’, denoting the number of test cases.
The first line of each test case contains one integer, ‘N’, denoting the number of stores.
The second line of each test case contains an array ‘money’ of ‘N’ space-separated integers, denoting the transaction amount carried out. If money[i] < 0, it means that Alex will pay |money[i]|, and if money[i] > 0, it means Alex will receive money[i] amount.
Output Format:
For each test case, print an integer denoting the maximum amount that Alex can have at any point.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 10^4
-10^5 <= money[i] <= 10^5
Time Limit: 1 sec
2
6
1 -3 5 -6 4 -3
1
11
3
11
In the first test case, the transaction values are [1, -3, 5, -6, 4, -3]. We can see that after the first transaction, the money left with Alex is 1. After the second, it is -2, then 3, then -3, then 1, and finally -2. We can see that after the third transaction, the money left with Alex is 3, which is the maximum money that he can have.
In the second test case, there is only one transaction. He receives 11 in the first transaction, which is also the highest that he can have.
2
5
5 7 11 3 5
3
-20 -19 -21
31
0
After each transaction, can you find the money left?
For each transaction, ‘i’ find the sum of all transactions ‘j’ such that j <= i. Update the maximum value as needed
The steps are as follows:
O(N ^ 2), where ‘N’ is the number of transactions.
For each transaction ‘i’ we are calculating the sum of transactions from j = 0 to j = i. Hence, the overall time complexity becomes O(N ^ 2).
O(1)
We are using constant space.