This is a question I came across on YouTube when I was learning about the sliding window problem.
Supposed you have an array like:
[1, 4, 3, 5, 6, 7, 1] // ret: 2 because 7+1 is the closest to target (while being >= to target)
1, 2, 3, 2, 1, 0, 8] // ret: 1 because 8 (esentially the basecase, is the perfect outcome).
However, when I tried to use the following:
array = [12, 2, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 2, 1, 3, 0];
target = 8;
console.log(smallestSubarraySize(array, target))I thought the result would be 5 because of the subarray [1, 1, 2, 1, 3] equals 8 in the smallest subset possible... Instead it returns **1. **
I don't have the instructions for the problem, but this doesn't seem like the output we should recieve.
function smallestSubarraySize(array, target){
let minSubSize = Infinity;
let currentSum = 0;
let pointA = 0;
for (let pointB = 0; pointB < array.length; pointB++){
currentSum += array[pointB];
while (currentSum >= target){
minSubSize = Math.min(minSubSize, pointB - pointA + 1 );
console.log(currentSum, pointB, );
currentSum -= array[pointA];
pointA++;
}
}
return minSubSize;
}