Question about leetcode #209

The problem is to find a contigous subarray that is larger or equal to the given target(https://leetcode.com/problems/minimum-size-subarray-sum/). I have got the solutions using sliding window and prefixSum.
What confuses me is my intuitive solution: first calculate sum of all the numbers marked as S. If S >= target, remove the smaller number of the nums[begin] and nums[end] ensuring current S to be largest of given length. When nums[begin] == nums[end], recursive is used.
When S < target, the loop ends and I can get the minLen. However, I get wrong answer dealing with the 18-th testcase(the input is too long to be pasted here). I don't know the problem lies in my algorithm or the implement.
Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums);
    int minSubArrayLen(int target, vector<int>& nums, int begin, int end, int S);
};

int Solution::minSubArrayLen(int target, vector<int>& nums)
{
	int S = accumulate(nums.begin(), nums.end(), 0);
	return minSubArrayLen(target, nums, 0, nums.size() - 1, S);
}

int Solution::minSubArrayLen(int target, vector<int>& nums, int begin, int end, int S)
{
	if (S < target || begin > end)
		return 0;
	while (S >= target && begin <= end)
	{
		if (nums[begin] > nums[end])
		{
			S = S - nums[end];
			--end;
		}
		else if (nums[begin] < nums[end])
		{
			S = S - nums[begin];
			++begin;
		}
		else
		{
			if (begin == end)
				return 1;
			int left = minSubArrayLen(target, nums, begin + 1, end, S - nums[begin]);
			int right = minSubArrayLen(target, nums, begin, end - 1, S - nums[end]);
			// left ==0 or right == 0 means that S >= target while S - nums[begin] or S - nums[end] is less than target
			return left == 0 || right == 0 ? end - right + 1 : min(left, right);
		}
	}
	return end - begin + 2;
}

Thanks for your help.
Last edited on
Is the test case too large to paste at say https://pastebin.com/ ?

Also beware that the URL parser on this site is pretty poor. It added some punctuation in your post.
https://leetcode.com/problems/minimum-size-subarray-sum/
One example when your algorithm fails is
target = 10
nums = [5, 3, 2, 6, 4]

Your algorithm always removes the smallest value from either end so the subarrays that it considers are the following:
[5, 3, 2, 6, 4] (sum=20)
[5, 3, 2, 6] (sum=16)
[3, 2, 6] (sum=11) <---
[2, 6] (sum=8)

It picks the subarray [3, 2, 6] which has a length of 3,
but [6, 4] with a length of 2 is a more optimal solution.
Last edited on
I have figured it out. Thanks for your answer.
Topic archived. No new replies allowed.