- Given one dimensional array in java.
- Calculate running sum of array.
Example to find running sum of array
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Algorithm to calculate running sum of array:
Calculate sum by modify original array:
- Loop through original array.
- Calculate sum of current element and sum of previous elements.
- Return original array
Calculate sum without modifying original array:
- Create new array equal to length of original array.
- int[] output = new int[nums.length]
- Copy first element from original array to new array.
- Loop through original array.
- Add current element of original array & sum of previous elements.
- output[iElement] = nums[iElement] + output[iElement-1] ;
- Return output array
Program to calculate running sum of array in java
package org.learn;
import java.util.Arrays;
public class RunningSumOfArray {
public static int[] runningSumCreateCopy(int[] nums) {
int[] output = new int[nums.length];
output[0] = nums[0];
for (int iElement = 1; iElement < nums.length; iElement++) {
output[iElement] = output[iElement - 1] + nums[iElement];
}
return output;
}
public static int[] runningSum(int[] nums) {
for (int iElement = 1; iElement < nums.length; iElement++) {
nums[iElement] += nums[iElement - 1];
}
return nums;
}
public static void main(String[] args) {
int[] nums = {1,2,3,4};
System.out.println("Input Array : "+Arrays.toString(nums));
System.out.println("Output Array:");
System.out.println(Arrays.toString(runningSumCreateCopy(nums)));
System.out.println(Arrays.toString(runningSum(nums)));
int[] arr = {1,1,1,1,1};
System.out.println("\nInput Array : "+Arrays.toString(arr));
System.out.println("Output Array:");
System.out.println(Arrays.toString(runningSumCreateCopy(arr)));
System.out.println(Arrays.toString(runningSum(arr)));
}
}
Output: calculate running sum of array in java
Input Array : [1, 2, 3, 4]
Output Array:
[1, 3, 6, 10]
[1, 3, 6, 10]
Input Array : [1, 1, 1, 1, 1]
Output Array:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]