Menu Close

Leetcode 1480: Running Sum of 1d Array Solution

Here, we will see how to solve Running Sum of 1d Array Solution of leet code 1480 problem.

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

You have to return the running sum of nums.

Example 1:

Input: nums = [1,2,3,4,5]
Output: [1,3,6,10,15]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5].

Example 2:

Input: nums = [1,1,1,1,1,1]
Output: [1,2,3,4,5,6]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1, 1+1+1+1+1+1].

Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

Running Sum of 1d Array Solution code in C++ and Go lang:

Here, we will be solving problem in multiple ways with code.

C++ code 1:

class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
        vector<int> v(nums.size());
        v[0] = nums[0];
        
        for(int i = 1; i < nums.size(); i++) {
            v[i] = nums[i] + v[i-1];
        }
        return v;
    }
};

C++ code 2:

class Solution {
public:
	vector<int> runningSum(vector<int>& nums) {
		int sum=0;
		
		for(int i=0;i<nums.size();i++){
			sum += nums[i];
			nums[i] = sum;
		}
		return nums;
	}
};

Go code 1:

func runningSum(nums []int) []int {    
    for i, _ := range nums {
        if i == 0 {
            continue
        }
        nums[i] += nums[i-1]
    }
    return nums
}

Go code 2:

func runningSum(nums []int) []int {
    size := len(nums)
    
    res := make([]int, size)
    
    res[0] = nums[0]
    
    for i := 1; i < size; i++ {
        res[i] = nums[i] + res[i-1]
    }
    return res
}

Output:

Input: nums = [1,2,3,4,5]
Output: [1,3,6,10,15]

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, golang, golang program, Leetcode

Leave a Reply

Your email address will not be published.

Contact Us