Alternating ledger
EasyOnline Assessment
Compute the final balance of a ledger whose entries alternate between being added and subtracted.
The balance starts at 0. The 1st amount is added, the 2nd is subtracted, the 3rd is added, the 4th is subtracted, and so on. Amounts may be negative, in which case the sign flips as usual (subtracting a negative amount increases the balance).
Input: amounts, a list of integers.
Output: an integer, the final balance. An empty list returns 0.
Example 1
- Input:
- [[10,4,7]]
- Output:
- 13
- Explanation
- Add 10, subtract 4, add 7: 10 - 4 + 7 = 13.
Example 2
- Input:
- [[-2,-5]]
- Output:
- 3
- Explanation
- Add -2, then subtract -5 (which adds 5): -2 + 5 = 3.
Example 3
- Input:
- [[100,40,30,20,10,5]]
- Output:
- 75
- Explanation
- Signs alternate +, -, +, -, +, -: 100 - 40 + 30 - 20 + 10 - 5 = 75.
Constraints
0 <= amounts.length <= 10,000-1,000,000 <= amounts[i] <= 1,000,000