Minimum Size Subarray Sum LeetCode
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Optimal Solution:
Optimized Sliding Window Approach (O(N))
Instead of checking all subarrays, we use a sliding window:
-
Expand the window (right pointer) until sum ≥ target.
-
Shrink the window (left pointer) while sum ≥ target.
-
Keep track of the minimum valid window size.
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, sum = 0, minLength = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right]; // Expand the window
while (sum >= target) { // Shrink from left if condition met
minLength = Math.min(minLength, right - left + 1); // Update min length
sum -= nums[left]; // Remove the leftmost element
left++; // Shrink the window
}
}
return (minLength == Integer.MAX_VALUE) ? 0 : minLength;
}
}
Brute Force :
Issue -Time limit exceeded
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int minLength = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int sum = 0; // Reset sum for new subarray
for (int j = i; j < n; j++) {
sum += nums[j];
if (sum >= target) {
minLength = Math.min(minLength, j - i + 1); // Fix length calculation
break; // No need to continue checking larger subarrays
}
}
}
return (minLength == Integer.MAX_VALUE) ? 0 : minLength; // Handle case when no subarray is found
}
}
Comments
Post a Comment