Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/f8d6985e44c87ddc53675cb749902b20 to your computer and use it in GitHub Desktop.
Save yitonghe00/f8d6985e44c87ddc53675cb749902b20 to your computer and use it in GitHub Desktop.
209. Minimum Size Subarray Sum (https://leetcode.com/problems/minimum-size-subarray-sum/): Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
// Two pointer solution: min/max substring template
// Time: O(n), 1ms
// Space: O(1), 37.9mb
class Solution {
public int minSubArrayLen(int s, int[] nums) {
// Window is [beign, end)
int begin = 0, end = 0, minLen = nums.length + 1, sum = 0;
while(end < nums.length) {
// Expand window to the right
sum += nums[end++];
while(sum >= s) {
// Update min length while it's still valie
minLen = Math.min(minLen, end - begin);
// Shrink the window from left
sum -= nums[begin++];
}
}
return minLen == nums.length + 1 ? 0 : minLen;
}
}
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums.length == 0) return 0;
int l = 0, r = 0, sum = nums[0], ans = nums.length + 1;
while(true) {
if(sum >= s) {
ans = Math.min(ans, r - l + 1);
sum -= nums[l++];
} else if(sum < s) {
++r;
if(r >= nums.length) break; //Check if the r is out of range
sum += nums[r];
}
}
if(ans == nums.length + 1) ans = 0;
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment