This problem asks for the total sum of all numbers in the array. Every element contributes to the result, so nothing is skipped.
Positive values increase the total, negative values reduce it, and zero leaves it unchanged. If the array is empty, the sum is simply 0 because there are no values to add.
For example, if nums = [1,2,3,4], the answer is 10. If nums = [10,-2,5], the answer is 13 because the negative value subtracts from the total. If all values are 0, the result stays 0.
So the task is to add every element in the array and return the final total.
Example Input & Output
Example 1: Sum of [1, 2, 3, 4] is 10
Example 2: Sum of [10, -2, 5] is 13
Example 3: Sum of [0, 0, 0] is 0
Algorithm Flow

Solution Approach
A straightforward running total is all we need. We start from zero and add each number to that total as we scan the array.
Initialize the answer:
Then process the numbers one by one:
Each step adds the current element into the running sum, so by the time the loop ends, total contains the sum of the whole array.
Then return it:
This solution runs in O(n) time and uses O(1) extra space.
Best Answers
class Solution {
public int sum_array(int[] nums) {
int sum = 0;
for (int num : nums) sum += num;
return sum;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
