DEV Community

Mayank Arora
Mayank Arora

Posted on

1480. Running Sum of 1d Array [Leetcode][C++]

All suggestions are welcome. Please upvote if you like it. Thank you.


Leetcode Problem Link: 1480. Running Sum of 1d Array


Brute Force Solution:

class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
    // Brute Force Solution Time O(N^2) & Auxiliary Space O(1)
    vector<int> result;
    int len=nums.size(),sum=0;
    for(int i=0;i<len;i++){
          sum=0;
        for(int j=0;j<=i;j++){
              sum+=nums[j];
        }
        result.push_back(sum);
    }
        return result;
    }
};
Enter fullscreen mode Exit fullscreen mode

Efficient Solution:

class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
    // Optimal Solution Time O(N) & Auxiliary Space O(1)
    int len=nums.size();
    for(int i=1;i<len;i++){
        nums[i]+=nums[i-1];
    }
        return nums;  
    }
};

Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

Top comments (0)