FundamentalsArrays
Total the Cart Amounts
Context
An online shop stores each cart amount as a signed number of cents. Positive entries represent product charges, while negative entries can represent refunds or discounts. The checkout service needs one function that combines every stored entry into the final order adjustment, including an empty cart.
Problem
Given an integer array of signed cart amounts in cents, return their total. Visit each entry exactly once and include every value in the addition, even when values repeat, are zero, or are negative. If the cart has no entries, return the additive identity. Do not remove duplicates or apply any special treatment based on an entry's sign.
Examples
Example 1
Input:
amounts = [1250, 799, 2100]Output:
4149Explanation: The executed result for [1250, 799, 2100] is 4149 after all three entries are processed.
Example 2
Input:
amounts = [500, -125, 0, -125, 850]Output:
1100Explanation: The executed result for [500, -125, 0, -125, 850] is 1100, including both negative entries and the zero entry.
Example 3
Input:
amounts = []Output:
0Explanation: The executed result for an empty array is 0.
Constraints
0 <= len(amounts) <= 1000-1000000 <= amounts[i] <= 1000000 for every i- Types:
amountsis int[]; result is int
Function signature
def total_cart_amounts(amounts: list[int]) -> int
amountslist[int]- Signed cart amounts in cents, with one entry for each recorded charge, discount, or refund.
- returns int
- The sum of all entries in amounts, or zero when the array is empty.
Code
Saved