PHP Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers)
Last Updated :
22 Jul, 2024
Given an unsorted array of nonnegative integers, find a continuous subarray that adds to a given number.
Examples:
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33
Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Output: Sum found between indexes 1 and 4
Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7
Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
There is no subarray with 0 sum
There may be more than one subarrays with sum as the given sum. The following solutions print first subarray.
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.
Example:
PHP
<?php
// A simple program to print subarray
// with sum as given sum
/* Returns true if the there is a
subarray of arr[] with sum equal
to 'sum' otherwise returns false.
Also, prints the result */
function subArraySum($arr, $n, $sum) {
$curr_sum; $i; $j;
// Pick a starting point
for ($i = 0; $i < $n; $i++) {
$curr_sum = $arr[$i];
// Try all subarrays starting
// with 'i'
for ($j = $i + 1; $j <= $n; $j++) {
if ($curr_sum == $sum) {
echo "Sum found between indexes ",
$i, " and ", $j-1 ;
return 1;
}
if ($curr_sum > $sum || $j == $n)
break;
$curr_sum = $curr_sum + $arr[$j];
}
}
echo "No subarray found";
return 0;
}
// Driver Code
$arr= array(15, 2, 4, 8, 9, 5, 10, 23);
$n = sizeof($arr);
$sum = 23;
subArraySum($arr, $n, $sum);
?>
OutputSum found between indexes 1 and 4
Complexity Analysis
- Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)
- Space Complexity: O(1). As constant extra space is required.
Efficient Approach
There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.
Algorithm
- Create three variables, l=0, sum = 0
- Traverse the array from start to end.
- Update the variable sum by adding current element, sum = sum + array[i]
- If the sum is greater than the given sum, update the variable sum as sum = sum - array[l], and update l as, l++.
- If the sum is equal to given sum, print the subarray and break the loop.
Example:
PHP
<?php
/* An efficient program to print
subarray with sum as given sum */
/* Returns true if the there is a
subarray of arr[] with sum equal
to 'sum' otherwise returns false.
Also, prints the result */
function subArraySum($arr, $n, $sum) {
/* Initialize curr_sum as value
of first element and starting
point as 0 */
$curr_sum = $arr[0];
$start = 0; $i;
/* Add elements one by one to curr_sum
and if the curr_sum exceeds the sum,
then remove starting element */
for ($i = 1; $i <= $n; $i++) {
// If curr_sum exceeds the sum,
// then remove the starting elements
while ($curr_sum > $sum and $start < $i - 1) {
$curr_sum = $curr_sum - $arr[$start];
$start++;
}
// If curr_sum becomes equal to
// sum, then return true
if ($curr_sum == $sum) {
echo "Sum found between indexes",
" ", $start, " ", "and ",
" ", $i - 1;
return 1;
}
// Add this element to curr_sum
if ($i < $n)
$curr_sum = $curr_sum + $arr[$i];
}
// If we reach here, then no subarray
echo "No subarray found";
return 0;
}
// Driver Code
$arr = array(15, 2, 4, 8, 9, 5, 10, 23);
$n = count($arr);
$sum = 23;
subArraySum($arr, $n, $sum);
?>
OutputSum found between indexes 1 and 4
Complexity Analysis:
- Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n).
- Space Complexity: O(1). As constant extra space is required.
Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details!
Similar Reads
PHP Program to Find the Size of Subarray With Maximum Sum Given an Array, the task is to find the size of the subarray that yields the maximum sum. This article provides a comprehensive guide on how to implement a PHP program to solve this problem efficiently.Examples: Input: Arr = [ 1, -2, 1, 1, -2, 1 ]Output: Length of the subarray is 2Explanation: The s
2 min read
PHP Program for Find the Subarray with Least Average Given an array Arr of size n and integer k such that k <= n, the task is to find the subarray with least average.Examples:Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: ar
3 min read
PHP Program for Largest Sum Contiguous Subarray Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum.  Recommended: Please solve it on âPRACTICE â first, before moving on to the solution.  Kadane's Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loo
4 min read
PHP Program for Number of pairs with maximum sum Write a PHP program for a given array arr[], count the number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j.Example:Input : arr[] = {1, 1, 1, 2, 2, 2} Output: 3 Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the
3 min read
PHP Program for Maximum Equilibrium Sum in an Array Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[].Examples: Input : arr[] = {-1, 2, 3, 0, 3, 2, -1}Output : 4Prefix sum of arr[0..3] = Suffix sum of arr[3..6]Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2}Output : 7Prefix sum of arr[0..3] = Suffix su
3 min read
PHP Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples:Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input : arr[] = {2, 5, 6, 7, 8, 8, 9};
3 min read