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.
1#include <stdio.h>
2
3void runningSum(int* nums, int numsSize, int* returnArr) {
4 int sum = 0;
5 for(int i = 0; i < numsSize; i++) {
6 sum += nums[i];
7 returnArr[i] = sum;
8 }
9}
10
11int main() {
12 int nums[] = {1, 2, 3, 4};
13 int numsSize = sizeof(nums) / sizeof(nums[0]);
14 int result[numsSize];
15
16 runningSum(nums, numsSize, result);
17
18 for(int i = 0; i < numsSize; i++) {
19 printf("%d ", result[i]);
20 }
21 return 0;
22}
This C program uses a function runningSum
which takes the original array nums
, its size, and an array returnArr
to store the running sums. An accumulator sum
keeps track of the cumulative total as we iterate over the array.
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.
1import java
In this Java implementation, the running sum is calculated directly within the input array, reducing the need for additional space.