Running Sum of 1d Array
Problem Statement
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.
Example:-
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
We need to calculate the running sum. The running sum at every index can be calculated by adding the element present at that index with the running sum till the previous index
i.e.
dp[i] =nums[i] + dp[i-1]
Here dp contains the running sum till the current index i.e. i.
vector<int> runningSum(vector<int>& nums) {
vector<int> ans;
ans.push_back(nums[0]);
for(int i=1;i<nums.size();i++)
{
ans.push_back(nums[i]+ans.back());
}
return ans;
}
Time Complexity:- O(n)
Space Complexity:- O(1)