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.
1using System;
2
3class RunningSum {
4 public static int[] CalculateRunningSum(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() {
15 int[] nums = {1, 2, 3, 4};
16 int[] result = CalculateRunningSum(nums);
17 Console.WriteLine(string.Join(", ", result));
18 }
19}
This C# program defines a method CalculateRunningSum
to compute the running sum. An accumulator keeps track of the total sum. The main method demonstrates usage of this function and displays results.
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.
1using System;
2
class RunningSum {
public static void CalculateRunningSum(int[] nums) {
for (int i = 1; i < nums.Length; i++) {
nums[i] += nums[i - 1];
}
}
public static void Main() {
int[] nums = {1, 2, 3, 4};
CalculateRunningSum(nums);
Console.WriteLine(string.Join(", ", nums));
}
}
This C# technique modifies the running sum in place, utilizing cumulative addition for the elements beyond the first.