Minimum Size Subarray Sum – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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
C++ Minimum Size Subarray Sum LeetCode Solution
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);
}
Java Minimum Size Subarray Sum LeetCode Solution
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);
}
Python 3 Minimum Size Subarray Sum LeetCode Solution
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)
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1
Leave a comment below