Sponsored
Sponsored
This approach involves iterating through the array nums
and calculating the running sum iteratively. Use an accumulator variable to keep the sum of elements encountered so far, and place this running sum into the result array.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(1) since we're modifying the array in place.
1import java.util.Arrays;
2
3public class RunningSum {
4 public static int[] runningSum(int[] nums) {
5 int sum = 0;
6 int[] result = new int[nums.length];
7 for(int i = 0; i < nums.length; i++) {
8 sum += nums[i];
9 result[i] = sum;
10 }
11 return result;
12 }
13
14 public static void main(String[] args) {
15 int[] nums = {1, 2, 3, 4};
16 int[] result = runningSum(nums);
17 System.out.println(Arrays.toString(result));
18 }
19}
In this Java program, the runningSum
method computes the running total by iterating through the input array nums
. An accumulator sum
keeps track of the sum, and result
array stores the running sums which is printed in the main method.
For the in-place approach, iterate through the array nums
, and update each position directly to the running sum. This method reduces space usage by avoiding the creation of a separate result array.
Time Complexity: O(n)
Space Complexity: O(1) since only the input array is modified.
1function
In this JavaScript solution, the running sum is computed directly on the input array, updating each element starting from the second position.