Minimum Size Subarray Sum Java Solution - The Coding Shala

Home >> Interview Question >> Minimum size subarray sum

Minimum Size Subarray Sum

Problem:

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.

Example: 

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.

Minimum Size Subarray Sum Java Solution

Approach:
Use two pointers.
Java 

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int len = Integer.MAX_VALUE, sum = 0, left=0;
        for(int i = 0; i<nums.length; i++){
            sum += nums[i];
            while(sum >= s){
                len = Math.min(len, i+1-left);
                sum -= nums[left];
                left++;
            }
        }
        return len == Integer.MAX_VALUE ? 0 : len;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala