Consider the following task statement:
Given an unsorted array of integers, find the subarray that is added to the given number. If there are multiple subarrays with the sum as the given number, print any of them.
Examples:
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4
Input: arr[] = {10, 2, -2, -20, 10}, sum = -10
Ouptut: Sum found between indexes 0 to 3
Input: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20
Ouptut: No subarray with given sum exists
The following linear temporary solution was proposed on this site using a map to store the sums of the current subsets as an iteration algorithm through an array:
void subArraySum(int arr[], int n, int sum)
{
unordered_map<int, int> map;
int curr_sum = 0;
for (int i = 0; i < n; i++)
{
curr_sum = curr_sum + arr[i];
if (curr_sum == sum)
{
cout << "Sum found between indexes "
<< 0 << " to " << i << endl;
return;
}
if (map.find(curr_sum - sum) != map.end())
{
cout << "Sum found between indexes "
<< map[curr_sum - sum] + 1
<< " to " << i << endl;
return;
}
map[curr_sum] = i;
}
cout << "No subarray with given sum exists";
}
int main()
{
int arr[] = {10, 2, -2, -20, 10};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = -10;
subArraySum(arr, n, sum);
return 0;
}
In the test case, which is indicated in the message, the second if statement checks if current_sum-sum will be present. Instead, the sum is found and printed in the first if statement. So here are a few confusions. :
1: What is the purpose of current_sum-suma map search ?
2: if, ?