Skip to content

Commit 9003988

Browse files
committed
running sum of 1d Array
LeetCode
1 parent 99c33c6 commit 9003988

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

run_sum.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Learn Python together
2+
3+
'''Given an array nums. We define a running sum of an array
4+
as runningSum[i] = sum(nums[0]…nums[i]).
5+
Return the running sum of nums. Input: nums = [1,2,3,4]
6+
Output: [1,3,6,10] -> [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]'''
7+
8+
# Solution
9+
def running_sum(nums):
10+
index = 0
11+
result = []
12+
# loping until index is equal to length of nums
13+
while index < len(nums):
14+
if index == 0:
15+
# getting the first number and adding it to the result
16+
num = nums[0]
17+
result.append(num)
18+
else:
19+
# adding sum of current and previous numbers to the result
20+
num = nums[index] + result[index-1]
21+
result.append(num)
22+
index += 1
23+
return result
24+
25+
# check
26+
print(running_sum([1,2,3,4])) # Output -> [1, 3, 6, 10]
27+
print(running_sum([3,1,2,10,1])) # Output -> [3, 4, 6, 16, 17]
28+
print(running_sum([1,1,1,1,1])) # Output -> [1, 2, 3, 4, 5]

0 commit comments

Comments
 (0)