0

Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

var runningSum = function(nums) {
    const array = new Array (nums.length);
    array[0] = nums[0];
    for( let i=1; i<nums.length; i++){
        array[i] = nums[i] + array[i-1]
    }
};

the result turns out to be undefine, I don't know where I did wrong.

1
  • 7
    you'll need to return array Commented Nov 7, 2020 at 23:16

2 Answers 2

2

You have to return the array

so

var runningSum = function(nums) {
    const array = new Array (nums.length);
    array[0] = nums[0];
    for( let i=1; i<nums.length; i++){
        array[i] = nums[i] + array[i-1]
    }
    return array;
};

instead of

var runningSum = function(nums) {
    const array = new Array (nums.length);
    array[0] = nums[0];
    for( let i=1; i<nums.length; i++){
        array[i] = nums[i] + array[i-1]
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

Here is another approach to solve the problem using recursion.

const nums = [1, 2, 3, 4];
const runningSum = (arr, result = [], sum = 0) => {
  if (arr.length === 0) return result;
  const tmp = sum + arr.shift();
  result.push(tmp);
  return runningSum(arr, result, tmp);
};
console.log(runningSum(nums));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.