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)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git