Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Solution:
[
class Solution {public int[] runningSum(int[] nums) {
int[] returnNumbers = new int[nums.length];
int counter = 0;
int num = 0;
for (int i = 0; i < nums.length ;i++){
num = 0;
for (int j = 0; j <= counter ; j++){
num = num + nums[j];
}
returnNumbers[i] = num;
counter++;
}
return returnNumbers;
}
}
]
Steps :
Here we have solved this problem using the brute force approach. In the first for loop, we iterate through the given array.
We save the sum of elements in an array in the variable num. Next, we run a second for loop through the elements of the array till i th element and add it and save it into the variable num.
The second loops run only till the variable counter. Once the second loop is finished running, we take the sum of i elements and save it in a new array and increment the counter once. Once the code has finished running we have an array that contains the sum till i th element.
Let me know your thoughts in the comments below.
COMMENTS