Given an array arr[] of integers, return the sum of all its elements.
Sum of Array
SolvedExamples:
Input: arr[] = [1, 2, 3, 4]
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10.
Input: arr[] = [10, -2, 7]
Output: 15
Explanation: 10 + (-2) + 7 = 15.
Constraints:
1 ≤ arr.size() ≤ 10^5-10^4 ≤ arr[i] ≤ 10^4
Expected Complexities
Time Complexity: O(n) Auxiliary Space: O(1)
Topic Tags
Keep a running total and add each element to it. The only trap is overflow: with a hundred thousand values of ten thousand each, the total no longer fits in a 32-bit integer, so use a 64-bit type in C, C++ and Java.
class Solution {
public:
long long sumOfArray(vector<int>& arr) {
long long total = 0;
for (int x : arr) total += x;
return total;
}
};
Sign in to see your submissions.