9.Minimum Size Subarray Sum >=k (positive no)

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation:The subarray [4,3] has the minimal length under the problem constraint

Algo:

This technique is similar toSliding Window Technique.

  1. Create variables, start=0, sum = 0

  2. Traverse the array from start to end.

  3. Update the variable sum by adding current element, sum = sum + array[i]

  4. If the sum is greater than the given sum, update the variable sum as sum = sum – array[start], and update start.

Solution : (Sliding Window)

class Solution
{
public:
    int minSubArrayLen(int s, vector<int> &nums)
    {
        int start = 0;
        int sum = 0;
        int i, minLen = INT_MAX;
        for (i = 0; i < nums.size(); i++)
        {
            sum = sum + nums[i];

            while (sum >= s)
            {
                if (i - start < minLen)
                {
                    minLen = (i - start);
                }
                sum = sum - nums[start];
                start++;
            }
        }
        
        if(minLen == INT_MAX){
            return 0;
        }
        else{
           return minLen+1;
        }
    }
};

Last updated