• Wednesday, 22-Jan-25 22:22:04 IST
Tech Trending :
* New DNA computer assesses water quality

Find subarray with given sum

Find subarray with given sum

Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.

Algorithm:  


Traverse the array from start to end.

From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.

For every index in inner loop update sum = sum + array[j]

If the sum is equal to the given sum then print the subarray.