For the question below: Given an array A of N non-negative numbers and a non-negative number B,you need to find the number of subarrays in A with a sum less than B.
I have found 2 solutions: Brute force:
let count = 0;
for (let i=0; i<A.length; i++) {
let sum = BigInt(0);
for (let j=i; j<A.length; j++) {
sum = sum + BigInt(A[j]);
if (sum < B) {
count+=1;
}
}
}
return count;
Optimised solution:
const countSubarrays = (A, B) => {
let start = 0;
let end = 0;
let ans = 0;
let currentSum = 0;
let n = A.length;
while (end < n) {
currentSum += A[end];
if (currentSum >= B) {
currentSum -= A[start];
start++;
}
ans += (end - start) + 1;
end++;
}
return ans;
}
const A = [2, 5, 6];
const B = 10;
const result = countSubarrays(A, B);
console.log('result: ', result);
But the result for optimised one is wrong. The formula to calculate all subarrays seems incorrect: ans += (end - start) + 1;
Could anyone please let me know the correct approach.
thanks