Table of Contents [hide]
Problem :
Given an array of positive integer and given value X, find Contiguous sub array whose sum is equal to X.
For example:
Solution:
Solution 1:
Check all sub arrays and if current sum is equal to X, return. This will require two loops and if currentSum is greater than X tben try another sub array.
Java code:
Time Complexity : O(N^2)
Solution 2:
Lets say array is arr[] and given sum is X.
- Iterate over array arr[].
- If currentSum is less than X then add current element to currentSum.
- If currentSum is greater than X , it means we need to remove starting elements to make currentSum less than X.
- If CurrentSum is equal to X, we got the continuous sub array, print it.
Java Code:
Java program to find the Contiguous Subarray with Sum to a Given Value in an array :
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.