标签:题目 int max span ima ring follow print instead
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguoussubarray 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.
1 public class Minimum_Size_Subarray_Sum { 2 public static int minSubArrayLen(int s, int[] nums) { 3 if(null==nums||nums.length==0){ 4 return 0; 5 } 6 7 int left = 0; 8 int minLeft = 0; 9 int minLen = nums.length; 10 int sum = 0; 11 int maxSum = Integer.MIN_VALUE; 12 13 for(int right=0;right<nums.length;right++){ 14 if(sum<s){ 15 sum += nums[right]; 16 if(sum>maxSum){ 17 maxSum = sum; 18 } 19 } 20 21 while(sum>=s){ 22 if(right-left+1<minLen){ 23 minLeft = left; 24 minLen = right - left + 1; 25 } 26 27 sum -= nums[left]; 28 left++; 29 } 30 } 31 32 if(maxSum<s){ 33 return 0; 34 } 35 36 return minLen; 37 } 38 39 public static void main(String[] args) { 40 int[] nums = {1,1,1,1,1,1}; 41 System.out.println(minSubArrayLen(6, nums)); 42 43 } 44 }
类似题目:
窗口最小子串问题 https://www.cnblogs.com/blzm742624643/p/10357757.html
LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题
标签:题目 int max span ima ring follow print instead
原文地址:https://www.cnblogs.com/blzm742624643/p/10359029.html