- 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
Product of subarray just less than target in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument, and a number, target, as the second argument.
Our function is supposed to count and return the number of (contiguous) subarrays where the product of all the elements in the subarray is less than target.
For example, if the input to the function is
Input
const arr = [10, 5, 2, 6]; const target = 100;
Output
const output = 8;
Output Explanation
The 8 subarrays that have product less than 100 are −
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example
Following is the code −
const arr = [10, 5, 2, 6]; const target = 100; const countSubarrays = (arr = [], target = 1) => { let product = 1 let left = 0 let count = 0 for (let right = 0; right < arr.length; right++) { product *= arr[right] while (left <= right && product >= target) { product /= arr[left] left += 1 } count += right - left + 1 } return count }; console.log(countSubarrays(arr, target));
Output
8
Advertisements