MrainW's Home

All things come to those who wait!

0%

LeetCode 209. Minimum Size Subarray Sum

Question

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

https://leetcode.com/problems/minimum-size-subarray-sum/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, n = nums.length, res = Integer.MAX_VALUE, sum = 0;
for (int i = 0; i < n; i++){
sum += nums[i];
while (sum >= target){
res = Math.min(res, i - left + 1);
sum -= nums[left++];
}

}
return res == Integer.MAX_VALUE ? 0 : res;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(1)

Welcome to my other publishing channels