
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- All possible odd length subarrays JavaScript
- Program to find sum of all odd length subarrays in Python
- Largest sum of subarrays in JavaScript
- Sum of XOR of all subarrays in C++
- Program to find sum of medians of all odd length sublists in C++
- Subarrays product sum in JavaScript
- Find the Number of Subarrays with Odd Sum using C++
- All possible binary numbers of length n with equal sum in both halves?
- Print all subarrays with 0 sum in C++
- Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)
- Binary subarrays with desired sum in JavaScript
- JavaScript Total subarrays with Sum K
- Finding n subarrays with equal sum in JavaScript
- Sum of XOR of all possible subsets in C++
- Maximum Possible Sum of Products in JavaScript

Advertisements