# Program to find running sum of 1d array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums. The running sum of an array as rs[i] is sum of all elements from nums[0] to nums[i]. Finally return the entire running sum of nums.

So, if the input is like nums = [8,3,6,2,1,4,5], then the output will be [8, 11, 17, 19, 20, 24, 29], because

rs[0] = nums[0]
rs[1] = sum of nums[0..1] = 8 + 3 = 11
rs[2] = sum of nums[0..2] = 8 + 3 + 6 = 17
and so on

To solve this, we will follow these steps −

• n:= size of nums

• rs:= [nums[0]]

• for i in range 1 to n - 1, do

• nums[i] := nums[i] + nums[i-1]

• insert nums[i] at the end of rs

• return rs

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(prices):
n=len(nums)
rs=[nums[0]]

for i in range(1,n):
nums[i]+=nums[i-1]
rs.append(nums[i])
return rs

nums = [8,3,6,2,1,4,5]
print(solve(nums))

## Input

[8,3,6,2,1,4,5]

## Output

[8, 11, 17, 19, 20, 24, 29]
Updated on 17-May-2021 12:13:36