nums = [ 3, 1, 2, 10, 1 ]
runningSum = [ 3, 3+1, 3+1+2, 3+1+2+10, 3+1+2+10+1 ]
runningSum = [ 3, 4, 6, 16, 17 ]
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class RunningSum { public static void main(String args[]) { int[] nums = { 1, 2, 3, 4 }; int[] runningSum = findRunningSum(nums); for(int x: runningSum) System.out.print(x+" "); } public static int[] findRunningSum(int[] nums) { int[] runningSum = new int[nums.length]; int sum = 0; for(int i=0; i<nums.length; i++){ sum += nums[i]; runningSum[i]=sum; } return runningSum; } } |
Python
def runningSum(arr): result = [None] * len(arr) sum = 0 for i in range(0, len(arr)): sum += arr[i] result[i] = sum return result arr = [1, 2, 3, 4] print(runningSum(arr))