Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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.
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
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
Follow up: If you have figured out the O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.
public int minSubArrayLen(int s, int[] A) {
int i = 0, n = A.length, res = n + 1;
for (int j = 0; j < n; ++j) {
s -= A[j];
while (s <= 0) {
res = Math.min(res, j - i + 1);
s += A[i++];
}
}
return res % (n + 1);
}
int minSubArrayLen(int s, vector<int>& A) {
int i = 0, n = A.size(), res = n + 1;
for (int j = 0; j < n; ++j) {
s -= A[j];
while (s <= 0) {
res = min(res, j - i + 1);
s += A[i++];
}
}
return res % (n + 1);
}
def minSubArrayLen(self, s, A):
i, res = 0, len(A) + 1
for j in xrange(len(A)):
s -= A[j]
while s <= 0:
res = min(res, j - i + 1)
s += A[i]
i += 1
return res % (len(A) + 1)
In our experience, we suggest you solve this Minimum Size Subarray Sum LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Minimum Size Subarray Sum LeetCode Solution
I hope this Minimum Size Subarray Sum LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>