- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Left right subarray sum product - JavaScript
We are required to write a JavaScript function that takes in an array of numbers of length N (N should be even) and divides the array into two sub-array (left and right) containing N/2 elements each and do the sum of the subarrays and then multiply both the subarrays.
For example: If the input array is −
const arr = [1, 2, 3, 4]
Then the output should be −
(2+1) * (3+4) = 21
Example
Following is the code −
const arr = [1, 2, 3, 4] const subArrayProduct = arr => { const { length: l } = arr; const creds = arr.reduce((acc, val, ind) => { let { left, right } = acc; if(ind < l/2){ left += val; }else{ right += val; } return { left, right }; }, { left: 0, right: 0 }); return creds.left * creds.right; }; console.log(subArrayProduct(arr));
Output
Following is the output in the console −
21
Advertisements