#algorithm #search #array #leetcode

idea

A sliding window search allows to find continguous items in an array with a certain property. It works by using an upper and lower bound, and a counter accounting for the items properties.

Search for the minimum number of contiguous items adding up to a certain value.

public class Solution {
    public int MinSubArrayLen(int target, int[] nums) {
        var lowerBound = 0;
        var upperBound = -1;
        var sum = 0;
        var count = Int32.MaxValue;
        while(++upperBound < nums.Length) {
            sum += nums[upperBound];
            while (sum >= target) {
                count = Math.Min(count, upperBound - lowerBound + 1);
                sum -= nums[lowerBound++];
            }
        }
        return count == Int32.MaxValue ? 0 : count;
    }
}

references