the problem is : 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.
https://leetcode.com/problems/minimum-size-subarray-sum/description/
my solution :
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int sum = 0;
int n = nums.size();
for(int num:nums){
sum += num;
}
if(sum<target){
return 0;
}
if(sum==target){
return n;
}
int left = 0;
int right = n-1;
int ans = n;
while( left<=right && sum>target){
if(nums[left]<=nums[right]){
sum -= nums[left];
left++;
}
else{
sum -= nums[right];
right--;
}
if(sum >= target)
ans--;
}
return ans;
}
};
i dont understand why this code does not work. Like it does not works for very large test cases. Can anyone explain why this code does not work but the sliding windows solution works perfectly fine?
……………………………………………………………
Saibalik Chakraborty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.