

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- All possible odd length subarrays JavaScript
- Program to find sum of all odd length subarrays in Python
- Sum of XOR of all subarrays in C++
- Largest sum of subarrays in JavaScript
- Program to find sum of medians of all odd length sublists in C++
- Find the Number of Subarrays with Odd Sum using C++
- Subarrays product sum in JavaScript
- All possible binary numbers of length n with equal sum in both halves?
- Print all subarrays with 0 sum in C++
- Total possible ways of making sum of odd even indices elements equal in array in JavaScript
- JavaScript Total subarrays with Sum K
- Sum of XOR of all possible subsets in C++
- Binary subarrays with desired sum in JavaScript
- Maximum Possible Sum of Products in JavaScript
- Squared sum of n odd numbers - JavaScript
Advertisements