Last updated on October 25th, 2024 at 10:21 pm
Here, We see Minimum Size Subarray Sum LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Array, Binary Search, Two Pointers
Companies
Level of Question
Medium
Minimum Size Subarray Sum LeetCode Solution
Table of Contents
Problem Statement
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 totarget
. 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
1. Minimum Size Subarray Sum LeetCode Solution C++
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { int l = 0, r = 0, n = nums.size(), sum = 0, len = INT_MAX; while (r < n) { sum += nums[r++]; while (sum >= target) { len = min(len, r - l); sum -= nums[l++]; } } return len == INT_MAX ? 0 : len; } };
2. Minimum Size Subarray Sum LeetCode Solution Java
class Solution { public int minSubArrayLen(int target, int[] nums) { if (nums == null || nums.length == 0) return 0; int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE; while (j < nums.length) { sum += nums[j++]; while (sum >= target) { min = Math.min(min, j - i); sum -= nums[i++]; } } return min == Integer.MAX_VALUE ? 0 : min; } }
3. Minimum Size Subarray Sum Solution JavaScript
var minSubArrayLen = function(target, nums) { let left = 0; let right = 0; let sum = 0; let result = 0; while(right < nums.length) { sum += nums[right]; while(sum >= target) { let len = right - left +1; if(result === 0 || len < result) result = len; sum -= nums[left]; left++ } right++; } return result; };
4. Minimum Size Subarray Sum Solution Python
class Solution(object): def minSubArrayLen(self, target, nums): total = left = right = 0 res = len(nums) + 1 while right < len(nums): total += nums[right] while total >= target: res = min(res, right-left+1) total -= nums[left] left += 1 right += 1 return res if res <= len(nums) else 0