subarray sum in c++
// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>
using namespace std;
// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum(int a[], int n)
{
int initial_sum = 0;
return accumulate(a, a+n, initial_sum);
}
int main()
{
int a[] = {5 , 10 , 15} ;
int n = sizeof(a)/sizeof(a[0]);
cout << arraySum(a, n);
return 0;
}
// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum(vector<int> &v)
{
int initial_sum = 0;
return accumulate(v.begin(), v.end(), initial_sum);
}
int main()
{
vector<int> v{5 , 10 , 15} ;
cout << arraySum(v);
return 0;
}
/* A simple program to print subarray
with sum as given sum */
#include <bits/stdc++.h>
using namespace std;
/* Returns true if the there is a subarray
of arr[] with sum equal to 'sum' otherwise
returns false. Also, prints the result */
int subArraySum(int arr[], int n, int sum)
{
int 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) {
cout << "Sum found between indexes "
<< i << " and " << j - 1;
return 1;
}
if (curr_sum > sum || j == n)
break;
curr_sum = curr_sum + arr[j];
}
}
cout << "No subarray found";
return 0;
}
// Driver Code
int main()
{
int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 23;
subArraySum(arr, n, sum);
return 0;
}
// This code is contributed
// by rathbhupendra
/* An efficient program to print
subarray with sum as given sum */
#include <iostream>
using namespace std;
/* Returns true if the there is a subarray of
arr[] with a sum equal to 'sum' otherwise
returns false. Also, prints the result */
int subArraySum(int arr[], int n, int sum)
{
/* Initialize curr_sum as value of
first element and starting point as 0 */
int 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 && start < i - 1) {
curr_sum = curr_sum - arr[start];
start++;
}
// If curr_sum becomes equal to sum,
// then return true
if (curr_sum == sum) {
cout << "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
cout << "No subarray found";
return 0;
}
// Driver Code
int main()
{
int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 23;
subArraySum(arr, n, sum);
return 0;
}
// This code is contributed by SHUBHAMSINGH10