Minimum Size Subarray Sum Solution

Source: Internet
Author: User

Question

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 has the [4,3] minimal length under the problem constraint.

Solution 1--pointers

Following the thought of Slide window, we apply the pointers here to solve the problem, one for left and one for right.

If current sum >= target, left++;

If current sum < target, right--;

Remember to check the right index before getting nums[right], and sum value are nums[0] at beginning.

Time complexity O (n).

1  Public classSolution {2      Public intMinsubarraylen (intSint[] nums) {3         if(Nums = =NULL|| Nums.length = = 0)4             return0;5         intLength = nums.length, left = 0, right = 0, result = length, sum = nums[0];6          while(Right <length) {7             if(left = =Right ) {8                 if(Nums[left] >=s) {9                     return1;Ten}Else { Oneright++; A                     if(Right <length) -Sum + =Nums[right]; -                     Else the                          Break; -                 } -}Else { -                 if(Sum <s) { +right++; -                     if(Right <length) +Sum + =Nums[right]; A                     Else at                          Break; -}Else { -result = Math.min (result, Right-left + 1); -Sum-=Nums[left]; -left++; -                 } in             } -         } to         if(left = = 0 && sum <s) +result = 0; -         returnresult; the     } *}

Minimum Size Subarray Sum Solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.