Sum of Array

62.6k
0

Given an integer array nums, return the sum of all its elements.

Example 1

Input: nums = [1, 2, 3, 4, 5]

Output: 15

Explanation: 1 + 2 + 3 + 4 + 5 = 15

Example 2

Input: nums = [4, -2, 0, 7, -3]

Output: 6

Explanation: 4 + (-2) + 0 + 7 + (-3) = 6

Approach

Maintain a running sum while traversing the array.

The running sum begins at 0. Each element is added to it once, so after the traversal, it represents the total of the complete array.

Algorithm

  • Initialize sum with 0, where it stores the running total. Starting from 0 works naturally because it does not affect addition.

  • Traverse nums once so that every element contributes exactly once to the final sum.

  • Add the current element to sum during each iteration, allowing positive, negative, and zero values to update the total naturally.

  • Return sum after all elements have been processed. If the array is empty, the initial value 0 is returned.

Dry Run

Sum of Array Elements Dry Run.png

Sum of Array Elements Dry Run.png

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Adds every array element to a running total.
long long arraySum(const vector<int>& nums) {
long long sum = 0;
// Each value contributes once to the final sum.
for (int value : nums) {
sum += value;
}
return sum;
}
};
int main() {
vector<int> nums = {3, -1, 2};
Solution solution;
cout << "Array sum: "
<< solution.arraySum(nums) << endl;
return 0;
}

Complexity Analysis

Time Complexity: O(N), where N represents the number of elements in the array. Every element is visited exactly once.

Space Complexity: O(1), because only one variable is maintained for the running sum.

Interview follow-up Questions

Yes. Every value is added normally. Negative numbers decrease the running sum, while zeros do not change it.

Arrays

Read Similar Blogs

Comments0