Sum of All Possible Odd Length Subarrays in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 27-Jan-2021 10:51:02
Advertisements