Skip to content

Commit 12904b9

Browse files
Running Sum of 1d Array
1 parent 612be83 commit 12904b9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

1480-Running-Sum-of-1d-Array.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
3+
Return the running sum of nums.
4+
5+
Example 1:
6+
Input: nums = [1,2,3,4]
7+
Output: [1,3,6,10]
8+
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
9+
10+
Example 2:
11+
Input: nums = [1,1,1,1,1]
12+
Output: [1,2,3,4,5]
13+
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
14+
15+
Example 3:
16+
Input: nums = [3,1,2,10,1]
17+
Output: [3,4,6,16,17]
18+
19+
Constraints:
20+
1 <= nums.length <= 1000
21+
-10^6 <= nums[i] <= 10^6
22+
'''
23+
24+
# Normal Iteration and Addition
25+
26+
class Solution:
27+
def runningSum(self, nums: List[int]) -> List[int]:
28+
res = [nums[0]]
29+
for num in nums[1:]:
30+
res.append(res[-1] + num)
31+
return res
32+
33+
# Normal Iteration and Addition in the Input Array
34+
35+
class Solution:
36+
def runningSum(self, nums: List[int]) -> List[int]:
37+
for i, num in enumerate(nums[1:]):
38+
nums[i+1] = nums[i]+num
39+
return nums
40+
41+
# Normal Iteration and Addition in the Input Array II
42+
43+
class Solution:
44+
def runningSum(self, nums: List[int]) -> List[int]:
45+
for i in range(1, len(nums)):
46+
nums[i] += nums[i-1]
47+
return nums

0 commit comments

Comments
 (0)