# LeetCode -- Minimum Size Subarray Sum

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

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

public class Solution {
public int MinSubArrayLen(int s, int[] nums)
{
int? min = null;

for(var i = 0;i < nums.Length; i++){
var l = MinLen(nums, i, s);
if(l.HasValue && l < min || min == null){
min = l;
}
}

return min.HasValue ? min.Value : 0;
}

private int? MinLen(int[] nums, int start, int target)
{
var s = 0;
var startFrom = start;
while(start < nums.Length){
s += nums[start];
if(s >= target){
return (start - startFrom + 1);
}
start ++;
}

return null;
}

}


1. 使用left和right两个指针分别从0作为起点
2. 如果当前s小于target，right一直往后走，直到s大于或等于target
3. 如果s大于等于target，left一直往后走，同时判断left与right的距离，更新最小窗口的大小。

http://www.geeksforgeeks.org/minimum-length-subarray-sum-greater-given-value/

public class Solution {
public int MinSubArrayLen(int s, int[] nums)
{
var len = nums.Length;
var sum = 0;
int? min = null;

// use two pointers
var start = 0;
var end = 0;

while (end < len)
{
// if current sum if smaller , keep moving right pointer forward
while (sum < s && end < len){
sum += nums[end];
end ++;
}

// if sum is more than target, keep moving left pointer forward to shrink the window size
while (sum >= s)
{
// find a smaller window then update size
if (!min.HasValue || end - start < min){
min = end - start;
}

// unload left most value from sum
sum -= nums[start];
start ++;
}

// now sum less than target again
// lets play again with the right pointer if not yet reach the end
}

return !min.HasValue ? 0 : min.Value;
}

}



• 本文已收录于以下专栏：

## Leetcode 209 - Minimum Size Subarray Sum（二分 or 双指针）

• Lzedo
• 2017年02月12日 20:35
• 117

## Minimum Size Subarray Sum - LeetCode 209

• bu_min
• 2015年05月24日 20:52
• 202

## [Leetcode]Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarr...

## 【leetcode】209. Minimum Size Subarray Sum

【leetcode】209. Minimum Size Subarray Sum

## Leetcode209-Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarra...

## Leetcode: Minimum Size Subarray Sum

﻿﻿ Given an array of n positive integers and a positive integer s, find the minimal length of a s...

## 51 leetcode - Minimum Size Subarray Sum

Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the ...
• lis_12
• 2016年12月21日 22:56
• 100

## 【leetcode】Array—— Minimum Size Subarray Sum（209）

举报原因： 您举报文章：LeetCode -- Minimum Size Subarray Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)