Leetcode 209: Minimum Size Subarray Sum

Source: Internet
Author: User

Leetcode 209: Minimum Size Subarray Sum
Minimum Size Subarray SumTotal Accepted:1954Total Submissions:8526

Given an arrayNPositive integers and a positive integerS, 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]Ands = 7,
The subarray[4,3]Has the minimal length under the problem constraint.

[Idea]

Two pointers, start end and end, go backward until sum is greater than s. Then start is backward until sum is less than s. min value is updated at the same time.

 

 

public class Solution {    //1,1,4    public int minSubArrayLen(int s, int[] nums) {        //init check        int start = 0;        int end = 0;                int sum = 0;        int min = Integer.MAX_VALUE;                while(start=s && start<=end) {                min = Math.min(min, end-start);                sum -= nums[start++];            }        }        return min==Integer.MAX_VALUE ? 0 : min;    }}

 

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.