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
sumwith0, where it stores the running total. Starting from0works naturally because it does not affect addition.Traverse
numsonce so that every element contributes exactly once to the final sum.Add the current element to
sumduring each iteration, allowing positive, negative, and zero values to update the total naturally.Return
sumafter all elements have been processed. If the array is empty, the initial value0is returned.
Dry Run
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.
Be the first to add a comment.