Intermediate Level
Implement the minimumSizeSubarraySum method that returns the smallest subarray length whose sum reaches the target.
The input contains a positive integer array nums, its length size, and a target sum target. Your task is to find the minimum length of a continuous subarray whose sum is at least target.
If no such subarray exists, return 0.
For example, in [2,3,1,2,4,3] with target 7, the subarray [4,3] has length 2, so the answer is 2.
Example 1
Input
nums (int[]) =
[2,3,1,2,4,3]size (int) =
6target (int) =
7Returns (int)
2Example 2
Input
nums (int[]) =
[1,4,4]size (int) =
3target (int) =
4Returns (int)
1Example 3
Input
nums (int[]) =
[1,1,1,1]size (int) =
4target (int) =
5Returns (int)
0Use a sliding window because the array contains positive numbers.
Expand the window by moving the right pointer and adding values to a running sum. When the sum becomes at least the target, try to shrink the window from the left to find a smaller valid length.
Keep the minimum valid length found. If no valid window is found, return 0.
Pseudocode:
function minimumSizeSubarraySum(nums, size, target):
left = 0
currentSum = 0
best = infinity
for right from 0 to size - 1:
currentSum = currentSum + nums[right]
while currentSum >= target:
best = minimum(best, right - left + 1)
currentSum = currentSum - nums[left]
left++
if best is infinity:
return 0
return bestReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run