Dynamic Programming - Part sum of elements JavaScript



Suppose, we have an array of numbers like this −

const arr = [1, 2, 3, 4, 5];

Taking one element less each time, this array can be separated out like this −

[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]

We are required to write a JavaScript function that takes in one such array. The function should separate out the array in the same way described above.

The function should then construct an array containing the respective sums of these parts and return that array.

Therefore, for this array, the output should look like −

const output = [15, 14, 12, 9, 5 0];

We will use Dynamic Programming to solve this problem. We will first calculate the sum of complete array in O(n) time, which eventually will become the first element of array. Then in another iteration, we will keep subtracting the corresponding elements to get the output array elements. This way we can solve this problem in O(n) time and O(1) space.

Example

const arr = [1, 2, 3, 4, 5];
const sumArray = (arr = []) => arr.reduce((a, b) => a + b, 0);
const partialSum = (arr = []) => {
   let sum = sumArray(arr);
   const res = [sum];
   for(let i = 0;
   i < arr.length; i++){
      const el = arr[i];
      sum -= el;
      res.push(sum);
   };
   return res;
};
console.log(partialSum(arr));

Output

This will produce the following output −

[ 15, 14, 12, 9, 5, 0 ]

Advertisements