简体   繁体   中英

Minimum size subarray

https://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/

I do not understand how this code works. As stated in the challenge the purpose is to

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.

Here is the code:

public int minSubArrayLen(int s, int[] nums) {
if(nums==null || nums.length==1)
    return 0;

int result = nums.length;

int start=0;
int sum=0;
int i=0;
boolean exists = false;

while(i<=nums.length){
    if(sum>=s){
        exists=true; //mark if there exists such a subarray 
        if(start==i-1){
            return 1;
        }

        result = Math.min(result, i-start);
        sum=sum-nums[start];
        start++;

    }else{
        if(i==nums.length)
            break;
        sum = sum+nums[i];
        i++;    
    }
}

if(exists)
    return result;
else
    return 0;
}

Here's the most straight forward way to go about the problem--though this is not going to be the most efficient algorithm to solve the problem.

You need the fewest number of elements in an array that sum up to something greater than some given number. Let's call the number of elements needed to do so s . Then the smallest value of s would occur when we take the largest few elements needed to surpass your minimum number.

Therefore the most direct solution would be to sort the array from greatest to least, and then loop through the elements until you surpass your minimum number. Then you would determine s from the index you stopped at.

The runtime complexity for this algorithm is O(nlogn) for the sorting portion, and then O(n) for the second portion. Thus the algorithm is O(nlogn) + o(n) = O(nlogn) run time complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM