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
Comments
Post a Comment