0
Subarray with given sum.
I was working on a question. https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0 Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S. This is my code. https://ide.geeksforgeeks.org/ScS1XcYPsm The approach I took was of sliding window. There is a test case in ide if whose output is 38 42. But when I reduce to last 14digits it gives correct output.
2 Respostas
+ 2
Let ex,
1
7 10
1 8 0 6 0 8 2
Sol -> i=1, start=1, end=2, sum=9
Sol -> i=2, start=1, end=3, sum=9
Sol -> i=3, start=2, end=4, sum=14
Sol -> i=5, start=3, end=4, sum=6
Sol -> i=6, start=3, end=5, sum=6
Sol -> i=7, start=4, end=6, sum=8
As you can see in above case you weren't able to check with all no.,
this because you are increasing and decreasing window size by only one at a time......
You should replace if with while on line no. 21 & 24 and also check for condition start and end is <= size....
This will greatly increase efficiency of code,
as you are adding element as long as sum is small
And removing element as long sum is large...
And also exit the loop once you found equal sum....
+ 1
One more thing, please take pain of copying code here from next time.....
It is very irritating, switch back and forth on SoloLearn and other site.....