Algorithms Problem Solving: Running Array Sum
TK
Posted on June 24, 2020
This post is part of the Algorithms Problem Solving series.
Problem description
This is the Running Array Sum problem. The description looks like this:
Given an array nums
. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i])
.
Return the running sum of nums
.
Examples
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Solution
The idea here is to cache the sum of the numbers while iterating through the list. For each number, add to the sum and then add the sum to the result list.
def running_sum(nums):
sum = 0
result = []
for num in nums:
sum += num
result.append(sum)
return result
Resources
💖 💪 🙅 🚩
TK
Posted on June 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
algorithms Algorithms Problem Solving: Construct Binary Search Tree from Preorder Traversal
June 17, 2020