Minimum Sub Array

By   Tewodros   Date Posted: Nov. 15, 2023  Hits: 308   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of numbers and a target, return the minimal length of a subarray whose sum is greater than or equal to target. Otherwise return 0.

Example:

nums =  {3, 5, 6, 2 , 5, 7} 

target = 12

Ans: 2

Explanation: the subarray 5,7 sum = 12.

We can use  sliding window approach. We will have two pointers I (left) and J(right). We increment j while calculating the sum of subarray between I and j is less than target. We then check if sum ≥ target, if so we calculate the distance between I and j and save it in a min variable. 

 

public class Solution {

   public  int MinSubArrayLen(int target, int[] nums) {

        int sum =0;

        int i=0, j=i+1;

        int min = Int32.MaxValue;

        sum = nums[0];

        while(i <nums.Length  && j <= nums.Length)

        {

            if(i > 0)

                sum = sum - nums[i-1];          

            while(sum<target && j < nums.Length)

            {   

                sum +=nums[j];              

                j++;

            }

            if(sum >= target)            

                min = Math.Min((j-i), min);

            

            i++;

        }

        return (min == Int32.MaxValue)?0:min;

    }

}

 

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* kzsndj

Back to Top