Sum of All Possible Odd Length Subarrays in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the only argument.

The function should first permute all possible subarrays from the original array that have an odd length. And then the function should find the combined sum of all the elements of those subarrays and return the sum.

For example −

If the input array is −

const arr = [1, 2, 3];

Then the output should be −

const output = 12;

because the desired subarrays are [1], [2], [3], [1, 2, 3]

Example

Following is the code −

const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3, 4, 5, 6];
const sumOfOddLengthSubarrays = (arr = []) => {
   let res = 0;
   for(let i = 0; i < arr.length; i++){
      let sum = 0;
      for(let j = i; j < arr.length; j++){
         sum += arr[j];
         if (((j - i + 1) & 1) === 0) {
            continue;
         };
         res += sum;
      }
   };
   return res;
};
console.log(sumOfOddLengthSubarrays(arr1));
console.log(sumOfOddLengthSubarrays(arr2));

Output

Following is the console output −

12
98

Updated on: 27-Jan-2021

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements