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.
1#include <vector>
2#include <iostream>
void runningSum(std::vector<int>& nums) {
for(int i = 1; i < nums.size(); i++) {
nums[i] += nums[i - 1];
}
}
int main() {
std::vector<int> nums = {1, 2, 3, 4};
runningSum(nums);
for(int num : nums) {
std::cout << num << " ";
}
return 0;
}
This C++ solution modifies the input vector in place to create the running sum starting from the second element, therefore space complexity is reduced.