Running Sum of 1d Array

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Find the running sum of nums

Example

Input: nums = [5,1,8,1]
Output: [5,6,14,15]
Explanation: Running sum is obtained as follows: [5, 5+1, 5+1+8, 5+1+8+1].

Approach

Java

import java.util.Arrays;

public class RunningSum {
    public static void main(String[] args) {
        int nums[] = { 5181 };
        nums = runningSum(nums);
        System.out.println("Running Sum is " + Arrays.toString(nums));
    }

    public static int[] runningSum(int[] nums) {
        if (nums.length < 2)
            return nums;

        for (int i = 1; i < nums.length; i++) {
            nums[i] = nums[i - 1] + nums[i];
        }
        return nums;
    }
}

// Time Complexity: O(n)
// Space Comlexity: O(1)

C++

#include <bits/stdc++.h>
using namespace std;
//Function to find running sum of
//the array
vector<intrunningSum(vector<int&arr)
{
   for(int i=1;i<arr.size();i++)
      arr[i]=arr[i-1]+arr[i];
   return arr;
}
int main()
{
   vector<intarr;
   arr.push_back(5);
   arr.push_back(1);
   arr.push_back(8);
   arr.push_back(1);
   arr=runningSum(arr);
   for(int i=0;i<arr.size();i++)
      cout<<arr[i]<<" ";
   return 0;
}
//Time Complexity: O(n)
//Space Complexity: O(1)


No comments:

Post a Comment