
- 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
Counting pairs with range sum in a limit in JavaScript
Range Sum
Range sum rangeSum(i, j) is defined as the sum of the elements in an array between indices i and j (i ≤ j), inclusive.
Problem
We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and two numbers, upper and lower as the second and third element.
Our function is supposed to return the number of range sums that lie between the range [upper, lower], (both inclusive).
For example, if the input to the function is −
const arr = [1, 4, 3]; const upper = 5; const lower = 2;
Then the output should be −
const output = 3;
Example
The code for this will be −
const arr = [1, 4, 3]; const upper = 5; const lower = 2; const countRangeSum = (arr = [], lower, upper) => { const sums = [0]; let res = 0; let last = 0; let firstge = value => { let l = 0, r = sums.length, m; do { m = Math.floor((r + l) / 2); sums[m] < value ? l = m : r = m; } while (r >= l + 2); while (r > 0 && sums[r - 1] >= value ) { r -= 1; } return r; }; arr.forEach(num => { last += num; res += firstge(last - lower + 1) - firstge(last - upper); sums.splice(firstge(last), 0, last); }); return res; }; console.log(countRangeSum(arr, lower, upper));
Output
The output in the console will be −
3
- Related Questions & Answers
- Counting adjacent pairs of words in JavaScript
- Map Sum Pairs in JavaScript
- Generating desired pairs within a range using JavaScript
- Program to count pairs with XOR in a range in Python
- Count pairs with given sum in C++
- Finding sum of a range in an array JavaScript
- Counting number of vowels in a string with JavaScript
- Counting pairs when a person can form pair with at most one in C++
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Sum of prime numbers between a range - JavaScript
- Print all pairs with given sum in C++
- Number of pairs with maximum sum in C++
- Finding sum of all numbers within a range in JavaScript
- Find all pairs that sum to a target value in JavaScript
- Find all the pairs with given sum in a BST in C++
Advertisements