Math, asked by Suma9670, 1 year ago

Number of contingous subarrays having sum exactly equal to k

Answers

Answered by hariharan108
0
The total number of subarrays. I want to count the number of subarrays for a vector (not combinations of elements). I think that for a vector of N elements the total number of subarrays is N*(N+1)/2 .
Answered by Anonymous
1

Answer:

Source: <a href="https://www.codingwithsid.in/2021/02/number-of-subarrays-having-sum-exactly-equal-to-k.html">source</a>

#include<iostream>

using namespace std;

int main()

{

   int arr[1000], k, n, ksum, currentsum, count = 0;

   cout<<"\n Enter number of elements:";

   cin>>n;

   cout<<"\n Enter array elements:";

   for (int i = 0; i < n; i++)

   {

       cin>>arr[i];

   }

   cout<<"\n Subarray sum equals:";

   cin>>ksum;

   for (int i=0; i<n; i++)

   {

       for(int j = i; j < n; j++)

       {

           currentsum=0;

           for(int k = i; k <= j; k++)

           {

               currentsum+= arr[k];

           }

           if ( currentsum == ksum)

           count++;

       }

   }

   cout<<"Total no. of subarray sum equals "<<ksum<<" is ";

   cout<<count;

   return 0;

   }

Similar questions