Let us understand why sliding will not work by using the following example:
[28,54,7,-70,22,65,-6]
100
curr_index=0, total_sum=28
curr_index=1, total_sum=82
curr_index=2, total_sum=89
curr_index=3, total_sum=19
curr_index=4, total_sum=41
curr_index=5, total_sum=106
curr_index=6, total_sum=100
Here the sum of the first six elements is 106, as our window size becomes bigger than 100 we will remove the element at 0th index (28) from it. But we could get 100 if we include -6 in the sum which would have made it to 100. Because of the negative numbers, the sum doesn't work as expected.
Now if the questions were to find a non-continuous subarray, then we could have sorted the array and used a sliding window technique which would have worked even with negative values as the sum would be always increasing and we won't get unpredictable sum.
Please help to UPVOTE if this post is useful for you.
If you have any questions, feel free to comment below.
HAPPY CODING :)
LOVE CODING :)