I encountered this question during an interview. It gives you an array and a threshold and the function should return the length of the shortest, non-empty, contiguous subarray of that array with sum at least past that threshold.
So if the array is [2,-1,2] and threshold is 3 then it should return 3 .
Here is my attempt written in JavaScript. I was taking a typical sliding window approach, where once the sum is bigger than threshold I will decrease the window size and I keep track of the window size during each iteration.
function(array, threshold) { let minWindowSize = Infinity let sum = 0 for (let start = 0, end = 0; end < array.length; end++) { sum += array[end] if(sum >= threshold) minWindowSize = Math.min(minWindowSize, end - start + 1) while (sum > threshold) { sum -= array[start--] } } return minWindowSize === Infinity ? -1 : minWindowSize }; However my solution is buggy for cases like
array = [17,85,93,-45,-21] threshold = 150 I wanted to know what differentiates this question from a typical sliding window question and is there a way to implement a sliding window approach to solve this question? It seems pretty straightforward but it turned out to be a hard question on leetcode.
https://stackoverflow.com/questions/66772752/algorithm-how-cant-i-use-sliding-window-approach-for-this-question March 24, 2021 at 07:33AM
没有评论:
发表评论